angularformsvalidationcustomvalidatorcustom-errors

how to get the type of error of a Validator


I have a simple input, I would like to get the type of error at submit.

  formGroup: FormGroup = this.fb.group({
     password: [
       '',
       [Validators.required, Validators.minLength(8), SpecialCharacters],
     ],
   });

For example:

   onSubmit(): void {
     if (this.formGroup.invalid) {
       //I get the type of error:
         //number of characters less than 8 
         //you have not entered any special characters
     } 
   }

Solution

  • You can use "hasError()" in order to specify what message you want to return for each respective error.

    example for the password field:

    onSubmit(): void {
      if (this.formGroup.invalid) {
        if (this.formGroup.get('password').hasError('minlength')) {
          console.log('number of characters less than 8 ');
        }
        if (this.formGroup.get('password').hasError('SpecialCharacters')) {
          console.log('you have not entered any special characters');
        }
      }
    }
    
    

    Another option is to access formGroup control errors, example for the password field:

    onSubmit(): void {
      if (this.formGroup.invalid) {
        if (!!this.formGroup.controls.password.errors?.minlength) { // force it to return false if error not found
          console.log('number of characters less than 8 ');
        }
        if (!!this.formGroup.controls.password.errors?.SpecialCharacters)) {
          console.log('you have not entered any special characters');
        }
      }
    }