有谁可以分享一个如何在Angular 2.4中为模板驱动表单创建自定义验证器的示例?
答案 0 :(得分:0)
有一篇文章演示了为被动和模板表单创建自定义验证规则。你可以在这里找到它 - https://angular.io/guide/form-validation#custom-validation-directive
答案 1 :(得分:0)
您可以为此创建一个指令,这是一个示例:
然后您可以在模板中使用它,如下所示:
<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;
}
答案 2 :(得分:0)
分享一个模板驱动的表单示例作为参考,可以帮助我理解,希望将来对某人有帮助
让我们创建一个如下所示的模板
<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>
在此示例中,对于自定义验证,创建了一个简单的指令,该指令实现了check,如果条件为true或返回验证错误对象,则返回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;
}
}
}