import { Validators, FormBuilder } from "@angular/forms";
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
validateForm = this.fb.group({
exchangePrice: [null, [Validators.required, this.greaterThanZeroValidator()]], });
greaterThanZeroValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
return value <= 0 ? { 'greaterThanZero': true } : null;
};
}
html
<mat-form-field>
<input
matInput
placeholder="兑换现金"
formControlName="exchangePrice"
required
type="number"
/>
<mat-error *ngIf="validateForm.get('exchangePrice')?.errors?.greaterThanZero">请输入大于0的数值</mat-error>
</mat-form-field>
a输入框输入的数不能大于b的
moreThanComNumberValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const value = control.value;
const comNumberVal = control.root.get("comNumber");
if (comNumberVal) {
return value > comNumberVal.value
? { moreThanComNumber: true }
: null;
}
};
}