3

I have a numeric input field in Angular reactive form.

 <input id="referenceNumber" type="number" formControlName="referenceNumber" />
 <div *ngIf="form.referenceNumber.invalid && (form.referenceNumber.dirty || form.referenceNumber.touched)">
    <span *ngIf="form.referenceNumber.errors?.required">
       Please Enter a number.
    </span>
 </div>

I want to show an error message on entering a value less than initial value. Do I need to create a custom validator or is there an easier way to do the same.

1
  • When you create the form, you add this initial value? Commented Mar 8, 2020 at 9:57

1 Answer 1

4

You set initial value on your input and you are use the built in Validators.min validator. You set as min number your initial value.

var initialValue: number;

this.form = this.fb.group({
    referenceNumber: [initialValue. 
    Validators.min(initialValue),
    Validators.pattern(/^[1-9]\d*$/) ])
});

html

<span *ngIf="myForm.get('referenceNumber').errors.min">
     numberInputName cannot be more than {{ initialValue }}. 
</span>

<span *ngIf="myForm.get('referenceNumber').errors?.pattern">
 numberInputName must be greater than zero
</span> 
Sign up to request clarification or add additional context in comments.

5 Comments

How can I show two separate error messages a) one for less than zero b) one for between zero and given range
If the number is less than zero you want a seperate error message?
@MadhurMaurya i update my answer with a second pattern validator which allow numbers greater than zero.
Thanks @Tzimpo I was trying the same. Won't it display both error messages when input it some negative number say (-1). I handled it by applying double checks in *ngIf such that only only validation passes through.
@MadhurMaurya Great!

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.