[英]Angular2 get existing validators of a formcontrol
可以說
surname = new FormControl('', [Validators.required, Validators.minLength(2)]);
在某些時候,我可能會根據情況添加或刪除有關姓氏控制的任何驗證器。
最后我怎么知道姓氏控制上存在哪些驗證器? 我在文檔中找不到任何東西,也沒有將控件轉儲到控制台
就像是
surname.getValidators() should return - ['required', 'minLength']
當前不支持從控件讀取驗證器
您可以顯示如下錯誤消息:
onValueChanged(data?: any) {
if (!this.heroForm) { return; }
const form = this.heroForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
formErrors = {
'name': '',
'power': ''
};
validationMessages = {
'name': {
'required': 'Name is required.',
'minlength': 'Name must be at least 4 characters long.',
'maxlength': 'Name cannot be more than 24 characters long.',
'forbiddenName': 'Someone named "Bob" cannot be a hero.'
},
'power': {
'required': 'Power is required.'
}
};
參考: https : //angular.io/docs/ts/latest/cookbook/form-validation.html#!#reactive-component-template
Günter Zöchbauer 的回答在 Angular 6 中仍然是正確的,但有一種解決方法對我很有效。
我的解決方法取決於兩個觀察結果:
首先,您可以通過查看errors
對象上的鍵來查看當前哪些驗證失敗。 因此,如果您指定了Validators.required
和Validators.minLength
,則錯誤對象將如下所示:
{ required: true, minlenght: { ... } }
這對於很多用例來說已經足夠了,當您並不真正關心驗證器是否存在但不會阻止表單提交時。
其次,事實證明 Angular 會創建驗證器來匹配輸入中設置的屬性。 所以對於標准驗證器,我的建議是根本不要指定驗證器。
做這樣的事情:
<input type="text" formControlName="surname" [required]="surnameRequired">
在您的表單聲明中:
form = this.formBuilder.group({
surname: '',
anotherField: ['', Validators.required],
yetAnotherField: ['', Validators.required]
});
然后設置surnameRequired
的值來添加或刪除驗證器。
我有一個可用的 StackBlitz 。
我的方法不適用於自定義驗證器,但我的大部分用例不使用這些。 你的旅費可能會改變。
我對讀取表單控件上的現有驗證器的需求略有不同。 我有一些動態應用驗證器的代碼,我想要一些單元測試來確保它正在做它應該做的事情。 但是由於您無法讀取驗證器,所以您有點搞砸了。
這就是我需要做的:
/**
* Validates that Validators.requires is applied ...
*/
it('should have a validator of required ...', () => {
component.functionThatShouldApplyValidator(true);
// Set the form control with an invalid value
component.formCtrl.setValue('');
// Expect the control to have an error { required: true }
expect(component.formCtrl.errors.required).toBeTrue();
});
有點長的路要走,但它的工作原理。
如果你想檢查一個表單控件是否有一些驗證器,你可以執行以下操作:
對於 Angular 內置驗證器,您可以使用:
if(control.validator == Validators.required)
對於自定義驗證器,它不起作用,您可以使用以下解決方法:
if(control.validator.toString() == customValidator().toString())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.