【问题标题】:How to set multi validation to form control?如何为表单控件设置多重验证?
【发布时间】:2020-01-04 11:54:17
【问题描述】:

我有一个带有 一个 输入的简单表单。我想在这个输入中设置多重验证。我可以为此设置一个验证,如下所示,但我想设置多个验证。请帮我 这是我的 HTML 代码:

   <form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
       <div class="input-holder">
          <input type="text" maxlength="11" inputmode="numeric" digitOnly formControlName="phoneNumber" />
          <input type="submit" value="دریافت لینک دانلود" [disabled]="!contactForm.valid">
       </div>
   </form>

这是 ts 文件:

contactForm: FormGroup;

  constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", [Validators.required])
    });
  }
 onSubmit() {
    console.log(this.contactForm.value);
  }

我要设置

Validators.minLength(11)

Validators.maxLength(11)

和...

【问题讨论】:

  • 你可以在数组中这样设置[Validators.required, Validators.minLength(11),Validators.maxLength(11)]

标签: angular forms validation angular-reactive-forms


【解决方案1】:

由于 FormControl validatorOrOpts 是数组,您可以像这样设置多个验证

constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", [Validators.required, Validators.minLength(11)])
    });
  }

或使用Validators.compose

将多个验证器组合成一个函数,该函数返回 所提供控件的各个错误映射的联合

 constructor() {
    this.contactForm = new FormGroup({
      phoneNumber: new FormControl("", Validators.compose([Validators.required, Validators.minLength(11)]))
    });
  }

【讨论】:

    【解决方案2】:

    完整的工作示例您可以在此StackBlitz Link 中找到,

    Thought, Answer 已经被接受并且有可行的解决方案我必须给出一个强大的解决方案来多次应用自定义验证.. 起初感觉很长,但在 Long - 应用程序扩展和可重用性的运行您可以多次重用您自己的自定义验证器函数。

    例如,如果您有密码字段,并且您想让该密码字段进行验证,如 PassWord 必须具有以下验证...

    • 必填
    • 至少允许一个小写字母
    • 至少允许一个大写字母
    • 至少允许一个数字字母
    • 至少允许一个特殊字符
    • 至少允许八个字母

    因此,在 Angular 中进行这种类型的多重验证时,我们将使用一个 custom-Validation-Function-directive 以获得更好的角度支持。创建新文件custom-validator.directive,然后在此文件中放入此代码...

    import{AbstractControl, ValidatorFn} from '@angular/forms';
    
    export function customValidation(): ValidatorFn{
          return (control: AbstractControl) : {[key:string]: boolean} | null =>{
                 const errorObject = {};
    
                 const SMALL_LETTER_REGEXP = /^(?=.*[a-z])/;
                 const UPPER_LETTER_REGEXP = /^(?=.*[A-Z])/;
                 const NUMERIC_REGEXP = /^(?=.*[0-9])/;
                 const SPECIAL_CHAR_REGEXP = /^(?=.*\W)/;
                 const AT_LEAST_EIGHT_REGEXP = /^(?=.{8,})/
    
                 if (SMALL_LETTER_REGEXP.test(control.value)){
                 }else {
                     errorObject['atLeastOneSmallLetter'] = true;
                  }
                 if (UPPER_LETTER_REGEXP.test(control.value)){
                 }else {
                    errorObject['atLeastOneUpperLetter'] = true;
                  }
                if(NUMERIC_REGEXP.test(control.value)){
                }else {
                    errorObject['atLeastOneNumeric'] = true;
                }
                if(SPECIAL_CHAR_REGEXP.test(control.value)){
                }else {
                    errorObject['atLeastOneSpecialChar'] = true;
                }
                if(AT_LEAST_EIGHT_REGEXP.test(control.value)){
                }else {
                    errorObject['atLeastOneEightLength'] = true;
                }
             return errorObject;
          };
    }
    

    现在将此文件导入到您的 formsGroupFormsBuilder 所在的 component.ts 中...

    import {customValidation} from './custom-validator.directive';
    
    export class AppComponent  {
        formGroup: FormGroup;
        constructor(private fb: FormBuilder){}
        ngOnInit(){
            this.formGroup = this.fb.group({
                                 password: ['', [ Validators.required,  customValidation()]]
                })
        }
        get password(){
            return this.formGroup.get('password');
        }
    }
    

    在上面password: ['', [ Validators.required, customValidation()]]这一行的代码中,我们将customValidation()函数传递给formGroup。这样,我们将在此 password 表单控件中应用所有验证。

    因此,每一个输入键域的变化,我们都会异步检查所有密码规则验证。并告诉用户只输入有效的密码匹配字符串...

    您的 Template.HTML

    <form [formGroup]="formGroup">
         <div  class="form-group col-md-6">
             <label for="password">Enter Pass-Word</label>
             <input id="password" class="form-control" placeholder="Password" type="password" formControlName="password" >
    
         </div>
    
         <div class="col-md-6 " *ngIf="password.invalid && (password.dirty || password.touched)">
             <div class="alert alert-danger " *ngIf="password.hasError('required')">
                <ul> <li> Required  </li> </ul>
             </div>
             <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneSmallLetter')">
                <ul> <li> At least one SMALL letter is allowed  </li> </ul> 
             </div>
             <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneUpperLetter')">
                <ul> <li> At least one UPPER letter is allowed  </li> </ul>
             </div>
             <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneNumeric')">
                <ul> <li> At least one NUMERIC letter is allowed  </li> </ul>
             </div>
             <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneSpecialChar')">
                <ul> <li> At least one SPECIAL-CHARACTER is allowed  </li> </ul>
             </div>
             <div class="alert alert-danger" *ngIf="password.hasError('atLeastOneEightLength')">
                <ul> <li> At least Eight Letter is allowed  </li> </ul>
             </div>
         </div>
    </form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      相关资源
      最近更新 更多