如何根据变量的当前值验证输入(自定义验证器函数)



我的表单上有一个输入字段,需要验证该数字是否不大于1000000且不小于帐户余额。我可以设置1000000的最大值,但无法成功地将余额与输入进行比较。我希望这能在输入字段周围产生一个红色的轮廓,类似于超过1000000时的轮廓。这是我的代码:

HTML模板

<mat-form-field appearance = outline class="amount">
<mat-label>Amount</mat-label>
<input matInput
type='number'
required 
formControlName="amount">
</mat-form-field>

组件

export class StartComponent implements OnInit {
currentAccount: ICustomerAccount;
amountMax = 1000000;
startForm = new FormGroup({
amount: new FormControl('', Validators.max(this.amountMax)),
});
}

您需要一个CustomValidator函数,如下所述:https://angular.io/guide/form-validation

@Component({
selector: 'app-validator-test',
templateUrl: './validator-test.component.html'
})
export class ValidatorTestComponent implements OnInit {
public startForm: FormGroup;
public amountMax = 5000;
public currentAccount: any = {value: 10};
constructor(private formBuilder: FormBuilder) {}
public ngOnInit(): void {
this.startForm =  this.formBuilder.group({
amount: ['', [Validators.max(this.amountMax), this.customValidatorFn()]]
});
}
private customValidatorFn(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const valid: boolean = this.currentAccount.value <= control.value;
return valid ? null : {amountMinError: true};
};
}
}

模板:

<form [formGroup]="startForm" *ngIf="startForm">
<input formControlName="amount" type="number"/>
<div>valid: {{startForm.get('amount').valid}}</div>
</form>

不要忘记将FormsModule和ReactiveFormsModule:imports: [BrowserModule, FormsModule, ReactiveFormsModule],添加到模块导入中

相关内容

  • 没有找到相关文章

最新更新