![](/img/trans.png)
[英]Compare the values of 2 input fields to validate the form in Angular 7 through the template
[英]Angular 5: Validate multiple input fields by sum up values
我想通過總結它們的值來驗證多個數字輸入字段,並為Angular創建一個自定義驗證器。
每個輸入看起來像這樣:
<input type="number" min="0" max="10">
有多個數字輸入,每個人都可以有0到10之間的值,但所有字段的總和必須小於或等於10。
我有一個函數,如果所有輸入字段的總和小於或等於10,則返回true。但是我如何使用自定義Angular驗證器實現此目的? 這樣就可以立即顯示錯誤消息。
就像在組本身上提到的設置驗證一樣,例如:
this.myForm = fb.group({
field1: [null],
field2: [null]
// more fields
}, {validator: this.myValidator})
然后在您的驗證器中迭代組中的formcontrols,總結並返回錯誤或基於有效或null
:
myValidator(group: FormGroup) {
let sum = 0;
for(let a in group.controls) {
sum += group.get([a]).value;
}
return sum > 10 ? { notValid: true} : null
}
在模板中,您可以顯示錯誤:
*ngIf="myForm.hasError('notValid')"
假設您正在使用上面提到的反應形式( https://angular.io/guide/reactive-forms ),您可以創建一個自定義驗證器,可以像這樣附加到組
this.formbuilder.group({...}, { validator: someCustomValidator })
自定義驗證器看起來像這樣
export const numberMatcher = (control: AbstractControl): {[key: string]: boolean} =>
{
const number = control.get('number');
const number2 = control.get('number2');
return number + number2 < 10 ? null : { exceedsmax: true };
};
哪個需要導入到您的組件(或存在於其中)
import { numberMatcher } from './numberMatcher';
ngOnInit() {
this.form = this.formbuilder.group({
number: ['', Validators.required],
number2: ['', Validators.required],
{ validator: emailMatcher })
});
}
然后正常設置表單,確保formControlName與驗證程序中檢查的名稱匹配。 然后,您可以檢查正常的錯誤,即
<div class="error" *ngIf="user.get('form').touched && user.get('form').hasError('exceededmax')">
All fields must equal less than 10
</div>
例如。 我認為本質上這將解決您的問題,但需要從我在這里寫的非常簡單的大綱代碼進行一些調整和調整。
如果您使用的是FormGroup
this.myForm = new FormGroup({
field1: new FormControl(null, Validators.required),
field2: new FormControl(null, Validators.required),
}, someCustomValidator);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.