我按照以下博客创建了自定义验证程序指令。 http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
通过Chrome调试器,我看到EmailValidator构造函数被调用,但是在我输入或当字段失去焦点时,从未调用validate()方法。
从以下博客提供代码。我注释掉了对EmailBlackList的引用。
<form novalidate>
...
<input type="email" name="email" ngModel validateEmail>
</form>
import {Directive, forwardRef} from '@angular/core';
import {NG_VALIDATORS, FormControl} from '@angular/forms';
function validateEmailFactory(/*emailBlackList: EmailBlackList*/) {
return (c: FormControl) => {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
};
}
@Directive({
selector: '[validateEmail][ngModel],[validateEmail][formControl]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => EmailValidator), multi: true }
]
})
export class EmailValidator {
validator: Function;
constructor(/*emailBlackList: EmailBlackList*/) {
this.validator = validateEmailFactory(/*emailBlackList*/);
}
validate(c: FormControl) {
return this.validator(c);
}
}