1

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 class="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)])
});

1 Answer 1

3

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

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

2 Comments

Its not working with input typ="number"
Would be great if you can create another question by providing a minimal reproducible (StackBlitz) example. As normally the answer is written based on the question.

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.