angularangular-reactive-formsangular2-form-validation

Angular Reactive Form Validation: Do not allow a number less than existing number


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.


Solution

  • 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>