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 ?
I succeeded by using 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 in my typescript code, I have :
this.rateControl = new FormControl("", [Validators.max(100), Validators.min(0)])
So, if we enter a value higher than 100 or smaller than 0, the material design input become red and the field is not validate. So after, if the value is not good, I don't save when I click on the save button.
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.
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.
If you are looking to validate length use minLength
and maxLength
instead.