15.《Angular表单校验》

2018-07-20  本文已影响0人  笨蛋小明

一、使用Angular自带的表单校验器

//react-regist.html
<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>电话:<input formControlName="mobile" type="text" name="mobile"/></div>
  <div>用户名:<input formControlName="username" type="text" name="username"/></div>
  <div formGroupName="passwordsGroup">
    <div>密码:<input formControlName="password" type="password" name="password"/></div>
    <div>确认密码:<input formControlName="confirmPass" type="password" name="confirmPass"/></div>
  </div>
  <div>
    <button type="submit">提交</button>
  </div>
</form>

//react-regist.ts
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {

  //这里是一个Angular的校验器
  xxxx(control: AbstractControl): { [key: string]: any } {
    return null;
  }

  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      mobile: ['18249666846'],
      username: ['xiaoming', [Validators.required, Validators.minLength(6)]],
      passwordsGroup: fb.group({
        password: [''],
        confirmPass: ['']
      })
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    let isVaild: boolean = this.formModel.get('username').valid;
    console.log('username的校验结果是:' + isVaild);

    let errors: any = this.formModel.get('username').errors;
    console.log('username的错误信息是:' + JSON.stringify(errors));

    console.log(this.formModel.value);
  }
}

运行结果:

运行结果1.png 运行结果2.png

二、自定义表单校验器

//修改react-regist.component.ts完成一个手机号验证器
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {

  mobileValidator(control: FormControl): any {
    var mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
    let vaild = mobileReg.test(control.value);
    console.log('mobile的校验结果是:' + vaild);
    return vaild ? null : {mobile: true};
  }

  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      mobile: ['', this.mobileValidator],
      username: ['', [Validators.required, Validators.minLength(6)]],
      passwordsGroup: fb.group({
        password: [''],
        confirmPass: ['']
      })
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    let isVaild: boolean = this.formModel.get('username').valid;
    console.log('username的校验结果是:' + isVaild);

    let errors: any = this.formModel.get('username').errors;
    console.log('username的错误信息是:' + JSON.stringify(errors));

    console.log(this.formModel.value);
  }
}
运行结果3.png
//修改react-regist.component.ts完成一个密码验证器
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {

  mobileValidator(control: FormControl): any {
    var mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
    let vaild = mobileReg.test(control.value);
    console.log('mobile的校验结果是:' + vaild);
    return vaild ? null : {mobile: true};
  }

  equalValidator(group: FormGroup): any {
    let password: FormControl = group.get('password') as FormControl;
    let confirmPass: FormControl = group.get('confirmPass') as FormControl;
    let vaild = (password.value === confirmPass.value);
    console.log('密码校验结果是:' + vaild);
    return vaild ? null : {equal: true};
  }

  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      mobile: ['', this.mobileValidator],
      username: ['', [Validators.required, Validators.minLength(6)]],
      passwordsGroup: fb.group({
        password: [''],
        confirmPass: ['']
      }, {validator: this.equalValidator})
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    let isVaild: boolean = this.formModel.get('username').valid;
    console.log('username的校验结果是:' + isVaild);
 
    let errors: any = this.formModel.get('username').errors;
    console.log('username的错误信息是:' + JSON.stringify(errors));

    console.log(this.formModel.value);
  }
}
运行结果4.png

当然我们也可以将验证器方法独立出来

//新建目录validator,新建validators.ts
import {FormControl, FormGroup} from '@angular/forms';

export function mobileValidator(control: FormControl): any {
  var mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
  let vaild = mobileReg.test(control.value);
  console.log('mobile的校验结果是:' + vaild);
  return vaild ? null : {mobile: true};
}

export function equalValidator(group: FormGroup): any {
  let password: FormControl = group.get('password') as FormControl;
  let confirmPass: FormControl = group.get('confirmPass') as FormControl;
  let vaild = (password.value === confirmPass.value);
  console.log('密码校验结果是:' + vaild);
  return vaild ? null : {equal: true};
}

//validators.ts
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {equalValidator, mobileValidator} from '../validator/validators';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {

  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      mobile: ['', mobileValidator],
      username: ['', [Validators.required, Validators.minLength(6)]],
      passwordsGroup: fb.group({
        password: [''],
        confirmPass: ['']
      }, {validator: equalValidator})
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    if (this.formModel.valid) {
      //只有当全部验证通过时才打印结构
      console.log(this.formModel.value);
    }
  }
}

使用hasError()在模版中显示

<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>用户名:<input formControlName="username" type="text" name="username"/></div>
  <div style="color: red" [hidden]="!formModel.hasError('required','username')">
    用户名是必填项
  </div>
  <div style="color: red" [hidden]="!formModel.hasError('minlength','username')">
    用户名最小长度是6位
  </div>
  <div>电话:<input formControlName="mobile" type="text" name="mobile"/></div>
  <div style="color: red" [hidden]="!formModel.hasError('mobile','mobile')">
    请输入正确的手机号码
  </div>
  <div formGroupName="passwordsGroup">
    <div>密码:<input formControlName="password" type="password" name="password"/></div>
    <div>确认密码:<input formControlName="confirmPass" type="password" name="confirmPass"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('equal','passwordsGroup')">
      密码和确认密码不匹配!
    </div>
  </div>
  <div>
    <button type="submit">提交</button>
  </div>
</form>

运行结果:

运行结果1.png 运行结果2.png 运行结果3.png
//修改react-regist.component.html密码验证
  <div formGroupName="passwordsGroup">
    <div>密码:<input formControlName="password" type="password" name="password"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('minlength',['passwordsGroup','password'])">
      密码最小长度是6位
    </div>
    <div>确认密码:<input formControlName="confirmPass" type="password" name="confirmPass"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('equal','passwordsGroup')">
      密码和确认密码不匹配!
    </div>
  </div>

//react-regist.component.ts修改
    this.formModel = fb.group({
      mobile: ['', mobileValidator],
      username: ['', [Validators.required, Validators.minLength(6)]],
      passwordsGroup: fb.group({
        password: ['', Validators.minLength(6)],
        confirmPass: ['']
      }, {validator: equalValidator})
    });

修改错误信息的返回方式

//修改react-regist.component.html密码验证
 <div formGroupName="passwordsGroup">
    <div>密码:<input formControlName="password" type="password" name="password"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('minlength',['passwordsGroup','password'])">
      密码最小长度是6位
    </div>
    <div>确认密码:<input formControlName="confirmPass" type="password" name="confirmPass"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('equal','passwordsGroup')">
      {{formModel.getError('equal','passwordsGroup')?.desc}}
    </div>
  </div>

//修改validator.ts
export function equalValidator(group: FormGroup): any {
  let password: FormControl = group.get('password') as FormControl;
  let confirmPass: FormControl = group.get('confirmPass') as FormControl;
  let vaild = (password.value === confirmPass.value);
  console.log('密码校验结果是:' + vaild);
  return vaild ? null : {equal: {desc:'两次密码输入不一致'}};
}

三、异步校验器

//validator.ts
import {FormControl, FormGroup} from '@angular/forms';
import {Observable} from 'rxjs/Observable';

export function mobileValidator(control: FormControl): any {
  var mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
  let vaild = mobileReg.test(control.value);
  console.log('mobile的校验结果是:' + vaild);
  return vaild ? null : {mobile: true};
}

export function mobileAnsyValidator(control: FormControl): any {
  var mobileReg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
  let vaild = mobileReg.test(control.value);
  console.log('mobile的校验结果是:' + vaild);
  return Observable.of(vaild ? null : {mobile: true}).delay(5000);
//这里用延时5s来模拟服务器返回
}

export function equalValidator(group: FormGroup): any {
  let password: FormControl = group.get('password') as FormControl;
  let confirmPass: FormControl = group.get('confirmPass') as FormControl;
  let vaild = (password.value === confirmPass.value);
  console.log('密码校验结果是:' + vaild);
  return vaild ? null : {equal: {desc: '两次密码输入不一致'}};
}

//react-regist.component.ts
import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {equalValidator, mobileAnsyValidator, mobileValidator} from '../validator/validators';

@Component({
  selector: 'app-react-regist',
  templateUrl: './react-regist.component.html',
  styleUrls: ['./react-regist.component.css']
})
export class ReactRegistComponent implements OnInit {

  formModel: FormGroup;

  constructor(fb: FormBuilder) {
    this.formModel = fb.group({
      mobile: ['', mobileValidator, mobileAnsyValidator],
      username: ['', [Validators.required, Validators.minLength(6)]],
      passwordsGroup: fb.group({
        password: ['', Validators.minLength(6)],
        confirmPass: ['']
      }, {validator: equalValidator})
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    // let isVaild: boolean = this.formModel.get('username').valid;
    // console.log('username的校验结果是:' + isVaild);
    //
    // let errors: any = this.formModel.get('username').errors;
    // console.log('username的错误信息是:' + JSON.stringify(errors));

    if (this.formModel.valid) {
      //只有当全部验证通过时才打印结构
      console.log(this.formModel.value);
    }
  }
}


//react-regist.component.html
<form [formGroup]="formModel" (submit)="onSubmit()">
  <div>用户名:<input formControlName="username" type="text" name="username"/></div>
  <div style="color: red" [hidden]="!formModel.hasError('required','username')">
    用户名是必填项
  </div>
  <div style="color: red" [hidden]="!formModel.hasError('minlength','username')">
    用户名最小长度是6位
  </div>
  <div>电话:<input formControlName="mobile" type="text" name="mobile"/></div>
  <div style="color: red" [hidden]="!formModel.hasError('mobile','mobile')">
    请输入正确的手机号码
  </div>
  <div formGroupName="passwordsGroup">
    <div>密码:<input formControlName="password" type="password" name="password"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('minlength',['passwordsGroup','password'])">
      密码最小长度是6位
    </div>
    <div>确认密码:<input formControlName="confirmPass" type="password" name="confirmPass"/></div>
    <div style="color: red" [hidden]="!formModel.hasError('equal','passwordsGroup')">
      {{formModel.getError('equal','passwordsGroup')?.desc}}
    </div>
  </div>
  <div>
    <button type="submit">提交</button>
  </div>
</form>
<div>
  {{formModel.status}}
</div>

运行结果:

初始值为INVALID.png 状态为pending.png 5s之后返回验证结果.png
上一篇下一篇

猜你喜欢

热点阅读