Min and max input value in angular4 app

I have an angular4 app with a form. In this case, I have an input to enter a percentage. So, I want to block the input with a value between 0 and 100. I tried to add min="0"

and max="100"

, but I can still enter a number higher than 100 or less 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?

+3


source to share


3 answers


I was able to use a form control. This is my html code:

    <md-input-container>
        <input type="number" min="0" max="100" required mdInput placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl">
        <md-error>Please enter a value between 0 and 100</md-error>
    </md-input-container>

      

And my typescript code has:



        this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])

      

So, if we enter a value greater than 100 or less than 0, the input for the material design turns red and the field is not checked. Therefore, if the value is not very good, I don't save when I click the Save button.

+6


source


In fact, when you use type = "number", your input control is filled with the help of up / down arrows to increase / decrease a numerical value, so when you update the value of the text field using this button, it will not limit passage 100 , but when manually enter the input like 120/130 etc. it will not check the maximum limit . >, so you need to check it by code.



You can disable manual input OR you need to write some code in the valueChange / textChange / key * event.

0


source


Here's the solution:

This is kind of a 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 a link to the plunker please take a look.

0


source







All Articles