我使用http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html中的示例实现了自定义验证程序指令:
import { Directive, forwardRef } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
function validateEmailFactory() {
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() {
this.validator = validateEmailFactory();
}
validate(c: FormControl) {
return this.validator(c);
}
}
然而,我想念的是失败标记。该字段标记为红色,但没有工具提示消息,例如需要字段时:
是否可以在验证器本身中附加此类消息?我找不到任何例子。
Sitenote:我正在使用PrimeNG,所以我认为标准的工具提示可能来自他们的扩展......