15.《Angular表单校验》

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

//react-regist.html
电话:
用户名:
密码:
确认密码:
//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); } }

运行结果:

15.《Angular表单校验》_第1张图片
运行结果1.png

15.《Angular表单校验》_第2张图片
运行结果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);
  }
}
15.《Angular表单校验》_第3张图片
运行结果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);
  }
}
15.《Angular表单校验》_第4张图片
运行结果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()在模版中显示

用户名:
用户名是必填项
用户名最小长度是6位
电话:
请输入正确的手机号码
密码:
确认密码:
密码和确认密码不匹配!

运行结果:

15.《Angular表单校验》_第5张图片
运行结果1.png
15.《Angular表单校验》_第6张图片
运行结果2.png
15.《Angular表单校验》_第7张图片
运行结果3.png
//修改react-regist.component.html密码验证
  
密码:
密码最小长度是6位
确认密码:
密码和确认密码不匹配!
//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密码验证
 
密码:
密码最小长度是6位
确认密码:
{{formModel.getError('equal','passwordsGroup')?.desc}}
//修改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
用户名:
用户名是必填项
用户名最小长度是6位
电话:
请输入正确的手机号码
密码:
密码最小长度是6位
确认密码:
{{formModel.getError('equal','passwordsGroup')?.desc}}
{{formModel.status}}

运行结果:

15.《Angular表单校验》_第8张图片
初始值为INVALID.png

15.《Angular表单校验》_第9张图片
状态为pending.png
15.《Angular表单校验》_第10张图片
5s之后返回验证结果.png

你可能感兴趣的:(15.《Angular表单校验》)