【问题标题】:Custom validator in Template driven forms for Angular 2.4Angular 2.4 模板驱动表单中的自定义验证器
【发布时间】:2017-12-02 08:39:05
【问题描述】:

谁能分享一个如何在 Angular 2.4 中为模板驱动的表单创建自定义验证器的示例?

【问题讨论】:

    标签: angular angular2-forms


    【解决方案1】:

    有一篇文章演示了为响应式表单和模板表单创建自定义验证规则。你可以在这里找到它 - https://angular.io/guide/form-validation#custom-validation-directive

    【讨论】:

    • 遗憾的是,该文档对于模板驱动表单上的自定义验证器来说已经过时了。
    【解决方案2】:

    您可以为此创建一个指令,这是一个示例:

    然后你可以在你的模板中使用它:

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

    【讨论】:

      【解决方案3】:

      分享一个模板驱动的表单示例以供参考,帮助我理解,希望它对将来的人有所帮助

      让我们创建一个如下所示的模板

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

      【讨论】:

        猜你喜欢
        • 2022-07-07
        • 1970-01-01
        • 2019-03-23
        • 2020-01-26
        • 1970-01-01
        • 2022-01-09
        • 2017-11-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多