How to create custom input component with validation in Angular?

263 Views Asked by At

I want to create custom component for input text but I don't know how can I bind validation of each input field to custom component. Is there any way to set errors of each field as array of objects like below

<app-custom-input
          formControlName="username"
          label="Username"
          [errors]="[
          { type: 'required', message: 'is required' },
          { type: 'minlength', message: 'min length error' }
        ]"
        ></app-custom-input>

stackblitz.io

1

There are 1 best solutions below

3
Giacomo Parolin On

You did most of the stuff already. The only missing thing is to correctly implement to your needs the validate function inside the custom component.

private readonly minLength = 3;

public validate(c: FormControl) {
    const errors: ValidationErrors[] = [];

    if (!c.value) {
      errors.push({error: "REQUIRED"});
    }

    if(c.value?.length < this.minLength) {
      errors.push({error: "MINLENGTH", minLength: this.minLength});
    }

    // Other validation logics...

    return errors;
}

Angular will take care of validating the control when the return array has length 0, while you can format the ValidationErrors shape to your needs.

Here is your code updated, with the current control.error and validity displayed below the input.

Sidenote: It would be nice to reference a ValidatorFn to validate the code instead of checking the control value itself, but unfortunately I was not able to do that.