Angular学习笔记(二十二)表单处理之校验器

自定义校验器

基本语法:

xxx(params:AbstractControl):{[key:string]}:any{
   renturn null;
}
  • 传入参数类型是AbstractControl,是FormGroupFormControlFormArray的共同父类,传入参数声明了校验器用于什么对象类型(前面提到的3种)上
  • 返回值类型为任意类型,其中返回对象类型中的key键是string类型,可通过errors打印

demo 1:

手机号校验

//编写手机号校验器

mobileVaild(mobile:FormControl):any{
    let value = (mobile.value|| "") +'';
    let myreg = /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/;
    let valid = myreg.test(value);
    console.log("手机号是否校验通过:"+valid)
    return valid ? null:{mobile:true}
}

//使用校验器

//配置表单数据模型,多个校验器使用数组形式

mobilephone:['',this.mobileVaild]

demo 2:

验证 密码和确认密码的 一致性

//编写校验器

passwordVaild(passwords:FormGroup):any{
    let passwordValue:FormControl = passwords.get("password") as FormControl;
    let pConfirmValue:FormControl = passwords.get("passwordConfirm") as FormControl;
    let valid:boolean =  passwordValue.value === pConfirmValue.value ;
    console.log("两次密码输入是否一致:"+valid);
    return valid?null:{passwords:{password:passwordValue.value,passwordConfirm:pConfirmValue.value}}
  }

//使用校验器
passwords:fb.group({
        password:[''],
        passwordConfirm:[]
      },{validator:this.passwordVaild})

//注册按钮打印错误信息
onSubmit(){
    console.log(this.formGroup.value);
    let passwordError = JSON.stringify(this.formGroup.get("passwords").errors);
    console.log(passwordError);
}

运行图:
Angular学习笔记(二十二)表单处理之校验器_第1张图片

Tips:FormGroup对象和FormArray对象的校验器是对象类型,其key是validator

Angular的内置校验器

内置校验器api

demo:
用户名必填且长度须大于6

//在数据模型中
username:['',[Validators.required,Validators.minLength(6)]]

//注册按钮
onSubmit(){
    let usernameValid:boolean = this.formGroup.get('username').valid;
    console.log("username是否校验通过:"+usernameValid);
    let usernameErrors = JSON.stringify(this.formGroup.get('username').errors);
    console.log("username的校验信息:"+usernameErrors);
}

Angular学习笔记(二十二)表单处理之校验器_第2张图片

封装成全局函数

validators/validators.ts

import { FormGroup , FormControl , FormArray , FormBuilder} from '@angular/forms';

export function mobileVaild(mobile:FormControl):any{
    let value = (mobile.value|| "") +'';
    let myreg = /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/;
    let valid = myreg.test(value);
    console.log("手机号是否校验通过:"+valid)
    return valid ? null:{mobile:false}
}

export function passwordVaild(passwords:FormGroup):any{
    let passwordValue:FormControl = passwords.get("password") as FormControl;
    let pConfirmValue:FormControl = passwords.get("passwordConfirm") as FormControl;
    let valid:boolean =  passwordValue.value === pConfirmValue.value ;
    console.log("两次密码输入是否一致:"+valid);
    return valid?null:{passwords:{password:passwordValue.value,passwordConfirm:pConfirmValue.value}}
}

你可能感兴趣的:(Angular学习系列)