我尝试使用html setcustomvalidity方法设置我的biz验证,但是该表单无法阻止自定义有效性。如何以角度使用此功能?
表格:
export class AutoComponent {
autoFiled: any;
@ViewChild('autoForm') autoForm;
@ViewChild('autoInput', { read: ElementRef}) autoInput: ElementRef;
check() {
if (autoField != '123') {
this.autoInput.nativeElement.setCustomValidity('Not Equals 123');
this.autoForm.submitted = true;
return false;
}
return true;
}
}
<form novalidate #autoForm="ngForm"
[class.invalid]="!autoForm.submitted">
<input #autoInput type="text" name="auto" [(ngModel)]="autoField"/>
</form>
答案 0 :(得分:1)
要以模板驱动的形式添加验证,您需要创建自定义指令
import { Directive } from '@angular/core';
import { NG_VALIDATORS, AbstractControl } from '@angular/forms';
@Directive({
selector: '[appCustomVaidator]',
providers:[{
provide: NG_VALIDATORS,
useValue: equalCheck,
multi: true
}],
exportAs:'appCustomVaidator'
})
export class CustomVaidatorDirective {
constructor() { }
}
function equalCheck(c:AbstractControl){
if(!c.value) return null;
return c.value != 123 ? { notEqual: true} : null;
}
Ref :: https://angular.io/guide/form-validation
示例:https://stackblitz.com/edit/angular-template-drive-form-customvalidator