Home > Mobile >  Angular - Validate numeric input field in the reactive form for specific range
Angular - Validate numeric input field in the reactive form for specific range

Time:08-05

In Angular form, there is a numeric input field. Here minimum value should be 3 and the max value is 10. When the form is loading, the default value should be 0. It means the user should be able to put 0 or values between 3 and 10. But my implementation gives an error when I send the form with the default value of 0. How can I solve this?

HTML page

<form #ConfigForm="ngForm" [formGroup]="sampleform" (ngSubmit)="onSendHandler()">
    <mat-form-field  appearance="outline">
    <input matInput formControlName="numValue"/>
    <mat-error *ngIf="sampleform.get('numValue').hasError('pattern')">Numbers Only ! 
    </mat-error>
    <mat-error *ngIf="sampleform.get('numValue').hasError('min')">Min Value is 
    3</mat-error>
    <mat-error *ngIf="sampleform.get('numValue').hasError('max')">Max Value is 
    10</mat-error>
   </mat-form-field>
</form>

.ts file

//set default values
this.sampleform.patchValue({
  numValue: 0
});

sampleform = new FormGroup({
numValue: new FormControl('', [Validators.pattern("^[0-9]*$"), Validators.min(3), 
Validators.max(10)])
});

CodePudding user response:

You need to implement a custom ValidatorFn which check the default value and range validators as below:

defaultValueOrRangeValidator(
  defaultValue: number,
  ...rangeValidators: ValidatorFn[]
): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value == defaultValue) return null;

    for (let validator of rangeValidators) {
      if (validator(control)) return validator(control);
    }
  };
}
this.sampleform = new FormGroup({
  numValue: new FormControl('', [
    ...
    this.defaultValueOrRangeValidator(
      0,
      Validators.min(3),
      Validators.max(10)
    ),
  ]),
});

Sample StackBlitz Demo

  • Related