Home > other >  minlength and maxlength, error validation in angular
minlength and maxlength, error validation in angular

Time:10-05

this.employeeForm = this.fb.group({
      fullName: [
        '',
        [
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(10),
        ],
      ],
      email: [''],
      skills: this.fb.group({
        skillName: [''],
        experienceInYears: [''],
        proficiency: [''],
      }),
    });

I am using the reactive form (angular) for validation and error showcase. But to show error message that, input entered by user is not between min and max criteria, I am facing problem.

<div >
            <input
              id="fullName"
              type="text"
              
              formControlName="fullName"
            />
            <p
              *ngIf="
                employeeForm.get('fullName')?.invalid &&
                employeeForm.get('fullName')?.touched
              "
            >
              please enter the valid full name
            </p>
            <p *ngIf="employeeForm.get('fullName')?.errors">  <-- I am not able to access the minLength and maxLength after errors , therefore not able to show case the error message also
              Full name should be under min and max
            </p>
          </div>
        </div>

how to showcase the error in case of error for min and max length. As after employeeForm.get('fullName')?.errors. no minLength / maxLenth nothing is coming.

thanks in advance

CodePudding user response:

the Toof_LD's answer is fine but if you would like to think about implementing more reusable code then please have a look at the custom validators. They are very easy to use, and once created, you can use anywhere in your application. Of course, this is a solution recommended when there is a lot of code checking the validation (such as in HTML) or when you need to perform more advanced validation.

Overall the syntax is very simple.

Syntax for a custom validator with no parameters:

function customValidator(control: AbstractControl): {[key: string]: boolean} | null {
   if(sthWrong) {
      return { yourValidatorName: true};
   }
    
   return null;
}

Syntax for a validator with parameters:

function customValidatorWithParameters(parameters: any): ValidatorFn {
   return(control: AbstractControl): {[key: string]: boolean} | null {
      if(sthWrong) {
         return { yourValidatorName: true};
      }
      
      return null;
   }
}

The best part is that it all comes down to checking in HTML that the control is valid (eg by a true or false value). Below is an example with a simple use of a custom validator with parameters. https://stackblitz.com/edit/angular-ivy-4tfvfd?file=src/app/app.component.ts

CodePudding user response:

Try this:

  • In .ts file:
get formControl(){
return this.employeeForm.controls;
}
  • in form template
<div >
    <input
            id="fullName"
            type="text"
            [ngClass]="{'is-invalid': isSubmitted && zaloControl.fullName.errors}"
            
            formControlName="fullName"
    />
    <div 
         *ngIf="isSubmitted && formControl.fullName.errors">
        <ng-container *ngIf="formControl.fullName.errors.minLength || formControl.fullName.errors.maxLength ">
            please enter the valid full name
        </ng-container>
    </div>
</div>
  • Related