角度4:自定义验证器不起作用 [英] angular 4 : custom validator not working
本文介绍了角度4:自定义验证器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从 angular 官方文档中提取了此示例。我注意到自定义验证可用于反应形式,但不适用于模板驱动的形式。
I pulled this example from angular official doc. I noticed that the custom validation is working with the reactive forms but it is not working with template-driven forms.
这里是提到的示例
指令:
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const forbidden = nameRe.test(control.value);
return forbidden ? {'forbiddenName': {value: control.value}} : null;
};
}
@Directive({
selector: '[appForbiddenName]',
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator {
@Input() forbiddenName: string;
validate(control: AbstractControl): {[key: string]: any} {
return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, 'i'))(control)
: null;
}
}
模板:
<form #heroForm="ngForm">
<div [hidden]="heroForm.submitted">
<div class="form-group">
<label for="name">Name</label>
<input id="name" name="name" class="form-control"
required minlength="2" forbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 2 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
</div>
</div>
</div>
</div>
</form>
推荐答案
您的指令称为appForbiddenName,所以
your directive it's called appForbiddenName, so
//in your directive
@Input('appForbiddenName') forbiddenName: string;
//In your template driven Form
<input id="name" ... appForbiddenName="bob" ...>
这篇关于角度4:自定义验证器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文