how to get the type of error of a Validator

2.1k Views Asked by At

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
     } 
   }
3

There are 3 best solutions below

3
Wahib Kerkeni On BEST ANSWER

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');
    }
  }
}
0
Ramana On

I'd try something like this for a specific formControl

get getPassword(): AbstractControl {
  return this.formGroup.get('password');
}

from the .html

<div *ngIf="getPassword.errors?.minLength">Minimum Length **</div>
<div *ngIf="getPassword.errors?.maxLength">Max Length ***</div>
1
Luca On

For the moment I have solved it like this:

 onSubmit(): void {
     if (this.formGroup.valid) {
       alert('Password salvata correttamente');
       this.formGroup.reset();
     } else {
       if (this.formGroup.controls.password.errors.minlength) {
         alert('ERROR MINLENGTH');
       }
       if (this.formGroup.controls.password.errors.specialCharacters) {
         alert(
           'ERROR SPECIALCHARACTERS'
         );
       }
     }
   }

Is it okay?