0

I am trying to do some Form Validations on my form using reactive form validation. However, I run into some issues when checking a field that is touched and dirty.

Brief Example:

HTML:

<input id="name" class="form-control"
      formControlName="name" required >

<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Percent is required.
  </div>

  <div *ngIf="name.invalid">
    Number must be between 0 and 1
  </div>

</div>

Typescript:

name: ['', [Validators.min(0.0001),Validators.max(0.9999),Validators.required]],

So my form logic is correct. If I enter a number not between 0 and 1, I get only one return that says Number must be between 0 and 1. However, the problem lies when I click the field and then click out. I get both errors that "Number is required" AND "Number must be between 0 and 1". How would I structure my logic so that only the error message "Number is required" displays?

5
  • 2
    instead of name.invalid use <div *ngIf="name.errors.max || name.errors.min"> Commented May 10, 2019 at 20:18
  • also it's good to use Validators.Compose([Validators.min(0.0001),Validators.max(0.9999),Validators.required]) for multiple validators Commented May 10, 2019 at 20:19
  • I changed it to <div *ngIf="name.errors.max || name.errors.min"> and it worked! Thanks a lot! Commented May 10, 2019 at 20:24
  • Can I post this as answer ? Can you accept it? Commented May 10, 2019 at 20:28
  • posted as answer Commented May 10, 2019 at 20:33

1 Answer 1

1

There is a small mistake in your *ngIf condition as you are using name.invalid which is always true for any kind of error. That's why you are seeing both messages at the same time.

instead of name.invalid change it to like below -

<input id="name" class="form-control"
      formControlName="name" required >

<div *ngIf="name.invalid && (name.dirty || name.touched)"
    class="alert alert-danger">

  <div *ngIf="name.errors.required">
    Percent is required.
  </div>

  <div *ngIf="name.errors.max || name.errors.min">
    Number must be between 0 and 1
  </div>

</div>

Now it will only show the message Number must be between 0 and 1 if the entered value is not between 0 and 1.

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

Comments

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.