代码之家  ›  专栏  ›  技术社区  ›  raju

如何在angular6中使用多个Regex模式验证器

  •  0
  • raju  · 技术社区  · 6 年前

    我正在尝试添加多个正则表达式模式的angular6反应形式。从一个答案我得到了这个

    ceInterfacename: new FormControl('', [
        Validators.required,
        this.regexValidator(new RegExp('^[0-9]+$'), {'number': ''})
      ]),
    

    和HTML格式

     <mat-form-field>
       <input matInput id='ceInterfacename' placeholder="CE Interface Name *"
          formControlName="ceInterfacename" [readonly]='isEditing && disableCeinterface()' />
       <mat-error
          *ngIf="peAddForm.controls.ceInterfacename.hasError('required') && (peAddForm.controls.ceInterfacename.dirty || peAddForm.controls.ceInterfacename.touched)">
          CE Interface Name is required
       </mat-error>
       <mat-error
          *ngIf="peAddForm.controls.ceInterfacename.hasError('number')">
          XYZ Interface Name is invalid
       </mat-error>
    </mat-form-field>
    

    XYZ接口名称无效

    但将输入突出显示为无效。

    请帮忙

    1 回复  |  直到 6 年前
        1
  •  2
  •   Robert    6 年前

    我认为您应该开始使用ErrorStateMatcher和CustomValidators,其中regex是在验证器中定义的。

    自定义验证器示例

    import {AbstractControl, ValidationErrors} from '@angular/forms';
    
    
    export class CustomValidators {
    
       static onlyWhitespace(control: AbstractControl): ValidationErrors | null {
        if ((control.value.trim() === '')) {
          return {onlyWhitespace: true};
        }
      }
    }
    

    错误状态匹配器可以在角度文档中找到

    https://material.angular.io/components/input/examples

    在表单组中设置验证程序:

    ceInterfacename: new FormControl('', [
        Validators.required,
        CustomValidators.youCusotmValidatorsName,
      ]), 
    

            <mat-error *ngIf="yourformControlname.hasError('you custom validators name')">Error text to show</mat-error>
    

    Stackblitz示例: https://stackblitz.com/edit/angular-material-2-nerwab

        2
  •  0
  •   riorudo    6 年前

    而不是 this.regexValidator(new RegExp('^[0-9]+$'), {'number': ''}) Validators.pattern(/^[0-9]+$/) . 当然,在模板中你必须检查 *ngIf="peAddForm.controls.ceInterfacename.hasError('pattern')" .

    另一种方法是应用自定义验证器(查看文档 https://angular.io/guide/form-validation 在“自定义验证器”下)。