[angular] Min and max value of input in angular4 application

I have an angular4 application with a form. In this one I have an input to enter a percentage. So, I want to block the input with value between 0 and 100. I tried to add min="0" and max="100" but I can yet enter an number higher than 100 or smaller than 0.

template

<md-input-container>
  <input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput" 
    name="rateInput">
  <md-error>Required field</md-error>
</md-input-container>

Do you know how I can do this ?

This question is related to angular input max min

The answer is


If you are looking to validate length use minLength and maxLength instead.


[I assume the reader has basic knowledge of Angular2+ and Forms]

It is easy to show a numerical input and put the limits, but you have to also take care of things may happen out of your predictions.

  1. Implement the tag in your 'html':
<input type="number" [min]="0.00" [max]="100.00" [step]="0.01" formControlName="rateFC">
  1. But as Adrien said, still user can enter manually a wrong number. You can validate input by Validators easily. In your '.ts':
import { FormGroup, FormControl, Validators } from '@angular/forms';

//many other things...

this.myFG = new FormGroup({
   //other form controls...,
   rateFC  : new FormControl(0, [Validators.min(0), Validators.max(100)])
});
  1. Up to now everything is ok, but it is better to let the user know the input is wrong, then draw a red line around the invalid input element by adding to your style:
.form-control.ng-touched.ng-invalid{
    border:2px solid red;
}
  1. And to make it perfect, prevent the user to submit the wrong data.
<button type="submit" [disabled]="!myFG.valid">Submit</button>

Here is the solution :

This is kind of hack , but it will work

<input type="number" 
placeholder="Charge" 
[(ngModel)]="rateInput" 
name="rateInput"
pattern="^$|^([0-9]|[1-9][0-9]|[1][0][0])?"
required 
#rateInput2 = "ngModel">

<div *ngIf="rateInput2.errors && (rateInput2.dirty || rateInput2.touched)"
    <div [hidden]="!rateInput2.errors.pattern">
        Number should be between 0 and 100
    </div>
</div>

Here is the link to the plunker , please have a look.


You can control with a change event if the input is within your range, if it is not in the range you assign 0.

<md-input-container>
  <input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput"
    (change)= "rateInput < 0 ? rateInput = 0 : rateInput; rateInput > 100 ? rateInput = 0 : rateIntput;"
    name="rateInput">
  <md-error>Required field</md-error>
</md-input-container>

Most simple approach in Template driven forms for min/max validation with out using reactive forms and building any directive, would be to use pattern attribute of html. This has already been explained and answered here please look https://stackoverflow.com/a/63312336/14069524


Actually when you use type="number" your input control populate with up/down arrow to increment/decrement numeric value, so when you update textbox value with those button it will not pass limit of 100, but when you manually give input like 120/130 and so on, it will not validate for max limit, so you have to validate it by code.

You can disable manual input OR you have to write some code on valueChange/textChange/key* event.


Simply do this in angular2+ by adding (onkeypress)

<input type="number" 
    maxlength="3" 
    min="0" 
    max="100" 
    required 
    mdInput 
    placeholder="Charge" 
    [(ngModel)]="rateInput"
    (onkeypress)="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
    name="rateInput">

Tested on Angular 7


You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz

@HostListener('change') onChange() {
  const min = +this.elementRef.nativeElement.getAttribute('min');

  if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
    this.renderer2.setProperty(
      this.elementRef.nativeElement,
      'value',
      min + ''
    );
  }
}

Also listen for the ngModelChange event to do the same when the form value is set.

@HostListener('ngModelChange', ['$event'])
onModelChange(value: number) {
  const min = +this.elementRef.nativeElement.getAttribute('min');
  if (this.valueIsLessThanMin(min, value)) {
    const formControl = this.formControlName
      ? this.formControlName.control
      : this.formControlDirective.control;

    if (formControl) {
      if (formControl.updateOn === 'change') {
        console.warn(
          `minValueDirective: form control ${this.formControlName.name} is set to update on change
          this can cause issues with min update values.`
        );
      }
      formControl.reset(min);
    }
  }
}

Full code:

import {
  Directive,
  ElementRef,
  HostListener,
  Optional,
  Renderer2,
  Self
} from "@angular/core";
import { FormControlDirective, FormControlName } from "@angular/forms";

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: "input[minValue][min][type=number]"
})
export class MinValueDirective {
  @HostListener("change") onChange() {
    const min = +this.elementRef.nativeElement.getAttribute("min");

    if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
      this.renderer2.setProperty(
        this.elementRef.nativeElement,
        "value",
        min + ""
      );
    }
  }

  // if input is a form control validate on model change
  @HostListener("ngModelChange", ["$event"])
  onModelChange(value: number) {
    const min = +this.elementRef.nativeElement.getAttribute("min");
    if (this.valueIsLessThanMin(min, value)) {
      const formControl = this.formControlName
        ? this.formControlName.control
        : this.formControlDirective.control;

      if (formControl) {
        if (formControl.updateOn === "change") {
          console.warn(
            `minValueDirective: form control ${
              this.formControlName.name
            } is set to update on change
              this can cause issues with min update values.`
          );
        }
        formControl.reset(min);
      }
    }
  }

  constructor(
    private elementRef: ElementRef<HTMLInputElement>,
    private renderer2: Renderer2,
    @Optional() @Self() private formControlName: FormControlName,
    @Optional() @Self() private formControlDirective: FormControlDirective
  ) {}

  private valueIsLessThanMin(min: any, value: number): boolean {
    return typeof min === "number" && value && value < min;
  }
}

Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.

 this.formGroup = this.formBuilder.group({
    test: [
      null,
      {
        updateOn: 'blur',
        validators: [Validators.min(5)]
      }
    ]
  });

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to max

Min and max value of input in angular4 application numpy max vs amax vs maximum mongodb how to get max value from collections Python find min max and average of a list (array) Max length UITextField How to find the highest value of a column in a data frame in R? MAX function in where clause mysql Check if all values in list are greater than a certain number How do I get the max and min values from a set of numbers entered? SQL: Group by minimum value in one field while selecting distinct rows

Examples related to min

Min and max value of input in angular4 application Python find min max and average of a list (array) How do I get the max and min values from a set of numbers entered? SQL: Group by minimum value in one field while selecting distinct rows How to exclude 0 from MIN formula Excel Using std::max_element on a vector<double> How can I get the max (or min) value in a vector? Most efficient way to find smallest of 3 numbers Java? Find the smallest amongst 3 numbers in C++ Obtain smallest value from array in Javascript?