简体   繁体   English

Angular 2.4 模板驱动表单中的自定义验证器

[英]Custom validator in Template driven forms for Angular 2.4

任何人都可以分享一个如何在 Angular 2.4 中为模板驱动表单创建自定义验证器的示例吗?

There is an article demonstrating creation of custom validation rule for both reactive and template forms.有一篇文章演示了为反应式表单和模板表单创建自定义验证规则。 You can find it here - https://angular.io/guide/form-validation#custom-validation-directive你可以在这里找到它 - https://angular.io/guide/form-validation#custom-validation-directive

You can create a directive for this and here is an example:您可以为此创建一个指令,这是一个示例:

在此处输入图片说明

Then you can use it in your template like here:然后您可以在您的模板中使用它,如下所示:

<input myCustomValidation [(ngModel)]="MyValue" #myValue="ngModel">

You can also add additional fields to your validation like this:您还可以向验证添加其他字段,如下所示:

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;
}

Sharing a template driven form example for reference that helped me to understand ,hope it will help someone in future分享一个模板驱动的表单示例以供参考,帮助我理解,希望它会在将来对某人有所帮助

Lets create a template as given below让我们创建一个如下所示的模板

<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>

For the custom validation in this example have created a simple directive that implements the check ,and returns null if condition is true or returns a validation error object ,the directive code is given below对于本例中的自定义验证,创建了一个简单的指令来实现检查,如果条件为真则返回 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;
    }
    
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM