美文网首页我爱编程
Angular表单验证

Angular表单验证

作者: _花 | 来源:发表于2018-06-01 11:57 被阅读0次

    angular的表单验证由验证器Validators模块提供,所以如果你的表单需要验证就要将此模块引入

    import { Validators} from '@angular/forms';
    

    一、想使用验证器需要做两件事

    1.为FormControl对象指定验证器;
    2.在试图中检查验证器状态,并根据状态来做不同的提示操作;

    //1.    对应代码
    //其中  match为  自定义验证器;
    validateForm : FormGroup;
      name:AbstractControl;
      constructor(private fb: FormBuilder,) { 
          this.validateForm = this.fb.group({
              formLayout: [ 'horizontal' ],
              name: ['', Validators.required],
              tell: ['',Validators.compose([Validators.required,match])],
              gender:['1',Validators.required],
             idCard:['', Validators.required],
          });
          this.name = this.validateForm.controls['name'];
      }
    
    // 2 对应的代码
    <form nz-form [nzLayout]="validateForm.get('formLayout')?.value" [formGroup]="validateForm" (ngSubmit)="submitForm()" novalidate >
            <nz-form-item>
                <nz-form-label >用户名</nz-form-label>
                <nz-form-control>
                    <input nz-input formControlName="name" placeholder="input placeholder">
                    <nz-form-explain *ngIf="name.dirty && name.errors">Please input your username!</nz-form-explain>
                </nz-form-control>
            </nz-form-item>
            <nz-form-item>
                <nz-form-label >手机号</nz-form-label>
                <nz-form-control >
                    <input nz-input formControlName="tell" placeholder="input placeholder">
                    <nz-form-explain *ngIf="validateForm.get('tell').dirty && validateForm.get('tell').errors && validateForm.controls['tell'].hasError('nomatch')">Please input your Password!</nz-form-explain>
                </nz-form-control>
            </nz-form-item>
            <nz-form-item>
                <nz-form-label >身份证</nz-form-label>
                <nz-form-control>
                    <input nz-input formControlName="idCard" placeholder="input placeholder">
                    <nz-form-explain *ngIf="validateForm.get('idCard').dirty && validateForm.get('idCard').errors ">Please input your Password!</nz-form-explain>
                </nz-form-control>
            </nz-form-item>
            <nz-form-item>
                <nz-form-label >性别</nz-form-label>
                <nz-radio-group formControlName="gender" nzName="radiogroup">
                    <label nz-radio nzValue="1">男</label>
                    <label nz-radio nzValue="2">女</label>
                </nz-radio-group>
            </nz-form-item>
            <nz-form-item>
                <nz-form-control >
                    <button nz-button nzType="primary">Submit</button>
                </nz-form-control>
            </nz-form-item>
        </form>
    

    二、在视图中引用FormControl有三种方法:

    1.如上面例子里的 name 属性;
    首先得引入AbstractControl这个抽象控制器模块用来表单验证,且将name设置为实例变量,而后将FormControl对象赋值给name。最后就可以在仕途上直接引用name 如:name.dirty && name.errors

    import {
      AbstractControl, //加入此语句
      FormBuilder,
      FormGroup,
      Validators
    } from '@angular/forms';
    ........
    name:AbstractControl;//将name设置为实例变量
    this.name = this.validateForm.controls['name'];//将FormControl对象赋值给name
    

    2.使用FormGroup对象的get()方法

    validateForm.get('tell').dirty ;
    

    3.使用FormGroup对象的controls()方法

    validateForm.controls['tell'].hasError('nomatch')
    

    三、自定义表单验证器

    自定义验证上述代码中 tell 手机号

    //nomatch.ts文件
    import {
      FormControl,
    } from '@angular/forms';
    export const match = (control: FormControl): {[key: string]: boolean} => {
      const tell = control.value;
       if(!(/^1(3|4|5|7|8)\d{9}$/.test(tell))){
          return { nomatch: true };
       }else {
          return null;//这里一定是null
       }
    };
    

    自定义表单验证器时需要用到Validators.compose在同一字段上添加多个验证器,如:

      tell: ['',Validators.compose([Validators.required,match])],
    

    而后便可以在视图中引用

    validateForm.controls['tell'].hasError('nomatch')
    

    四、Angular自带的验证器

    1.required()
    Validators.required
    2.min()
    Validators.min(3)
    3.max()
    Validators.max(15)
    4.email()
    Validators.email
    5.minLength()最小值
    Validators.minLength(4)
    6.maxLength()最大值
    Validators.maxLength(12)
    7.compose组合
    Validators.compose([Validators.required,match])
    8.pattern()正则
    Validators.pattern(RegExp)
    9.requiredTrue()value值为true
    Validators.requiredTrue

    相关文章

      网友评论

        本文标题:Angular表单验证

        本文链接:https://www.haomeiwen.com/subject/vpqcsftx.html