1

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.

1
  • 2
    Take a look at custom validators, angular.io/guide/form-validation#custom-validators. You can use these to set custom validation and then can listen for the error string and show your message. Commented Feb 17, 2020 at 13:27

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Ben, the first example only show an unique error message and you has an unique div. The customError defined only give you an unique error
But is there a way to loop over all of the existing errors, not manually creating div for each one but something like:. <div ngFor="let error ofmyform.get('control').errors">. <span>{{error.message}}</span>. </div>
the error is an object, so you need use the KeyValuePipe angular.io/api/common/KeyValuePipe, some like <div *ngFor="let error of myform.get('control').errors | keyvalue">{{error.key}}:{{error.value}}</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.