Angular learning notes (22) form processing verifier

Keywords: Mobile JSON angular

Custom verifier

Basic syntax:

xxx(params:AbstractControl):{[key:string]}:any{
   renturn null;
}
  • The type of the incoming parameter is AbstractControl, which is the common parent class of FormGroup, FormControl and FormArray. The incoming parameter declares what object type the validator is used for (the three mentioned above)
  • The return value type is any type, where the key key in the return object type is string type, which can be printed through errors

demo 1:

Mobile phone number verification

//Write cell phone number checker

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("Whether the mobile phone number passes the verification:"+valid)
    return valid ? null:{mobile:true}
}

//Use calibrator

//Configure form data model. Multiple validators use array form

mobilephone:['',this.mobileVaild]

demo 2:

Verify password and confirm password consistency

//Write calibrator

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("Whether the two password inputs are consistent:"+valid);
    return valid?null:{passwords:{password:passwordValue.value,passwordConfirm:pConfirmValue.value}}
  }

//Use calibrator
passwords:fb.group({
        password:[''],
        passwordConfirm:[]
      },{validator:this.passwordVaild})

//Register button print error message
onSubmit(){
    console.log(this.formGroup.value);
    let passwordError = JSON.stringify(this.formGroup.get("passwords").errors);
    console.log(passwordError);
}

Operation diagram:

Tips: the validator of FormGroup object and FormArray object is object type, and its key is validator

Internal calibrator of Angular

Built in verifier api

demo:
User name is required and must be longer than 6

//In the data model
username:['',[Validators.required,Validators.minLength(6)]]

//Registration button
onSubmit(){
    let usernameValid:boolean = this.formGroup.get('username').valid;
    console.log("username Pass verification or not:"+usernameValid);
    let usernameErrors = JSON.stringify(this.formGroup.get('username').errors);
    console.log("username Verification information of:"+usernameErrors);
}

Posted by suckablesausage on Sun, 05 Apr 2020 15:52:55 -0700