【发布时间】:2017-12-02 08:39:05
【问题描述】:
谁能分享一个如何在 Angular 2.4 中为模板驱动的表单创建自定义验证器的示例?
【问题讨论】:
谁能分享一个如何在 Angular 2.4 中为模板驱动的表单创建自定义验证器的示例?
【问题讨论】:
有一篇文章演示了为响应式表单和模板表单创建自定义验证规则。你可以在这里找到它 - https://angular.io/guide/form-validation#custom-validation-directive
【讨论】:
您可以为此创建一个指令,这是一个示例:
然后你可以在你的模板中使用它:
<input myCustomValidation [(ngModel)]="MyValue" #myValue="ngModel">
您还可以像这样在验证中添加其他字段:
validate(formGroup: FormGroup): ValidationErrors {
const passwordControl = formGroup.controls["password"];
const emailControl = formGroup.controls["login"];
// for example check if email and password fields have value
if (!passwordControl || !emailControl || !passwordControl.value || !emailControl.value) {
return null;
}
// do validation here using passwordControl.value and emailControl.value
return formGroup;
}
【讨论】:
分享一个模板驱动的表单示例以供参考,帮助我理解,希望它对将来的人有所帮助
让我们创建一个如下所示的模板
<input id="name" name="name" class="form-control"
required appValidator
[(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.appValidation">
Name cannot be Bob.
</div>
</div>
对于本例中的自定义验证,创建了一个简单的指令来实现检查,如果条件为真则返回 null 或返回验证错误对象,指令代码如下
import { Directive } from '@angular/core';
import{NG_VALIDATORS,ValidationErrors,Validator,AbstractControl} from '@angular/forms'
@Directive({
selector: '[appValidator]',
providers:[{provide: NG_VALIDATORS, useExisting: ValidatorDirective, multi: true}]
})
export class ValidatorDirective implements Validator {
constructor() { }
validate(control:AbstractControl):ValidationErrors|null{
const val = control.value;
if(val === "Bob"){
return {appValidation:"Bob is not allowed"};
}else{
return null;
}
}
}
【讨论】: