Ben Kalifa
Ben Kalifa

Reputation: 17

Reactive forms conditional custom validation

I'm using reactive form validation in angular, and I'm trying to add different messages for different
in-validities, for example if I have a score field that should be between 1-100, I want to have a message when the user enters a letter and a different message if he enters a number bigger than 100.

Is there a way to do it by creating an interface:

interface error {
     condition: boolean,
     message: string
}

using ngFor and iterating over a collection of errors, checking wether a condition is met?

The problem I have is that the condition is linked to function() : boolean, and ngFor does not renders itself again when the user enters an invalid input, since there is no change in the collection but in the value that the condition function will return.

Upvotes: 1

Views: 67

Answers (1)

Eliseo
Eliseo

Reputation: 57919

when you create a customValidator you return an object if an error happens. This object can be different acording your requeriments.

  customError() {
    return (control: AbstractControl) => {
      if (isNaN(control.value)) return { error: "it's not a number" };
      if (+control.value > 100) return { error: "it's greater than 100" };
      return null;
    };
  }

   <div *ngIf="myform.get('control').errors">
         {{myform.get('control').errors.error}}
   </div>

You can also return an object with diferents property,e.g. errorNaN and errorGt

  customError() {
    return (control: AbstractControl) => {
      if (isNaN(control.value)) return { errorNaN : "it's not a number" };
      if (+control.value > 100) return { errorGt: "it's greater than 100" };
      return null;
    };
  }

   <div *ngIf="myform.get('control').errors?.errorNaN">
      It's not a number
   </div>
   <div *ngIf="myform.get('control').errors?.errorGt">
      it's greater than 100
   </div>

a simple example stackblitz

Upvotes: 2

Related Questions