I have input type number, I want to restrict it to only numbers between 1 and 2. It can accept numbers between 0.00001 and 2 with decimal places up to 5 and not 0.
How do i do it? And also the user must not be able to write anything else manually.
I have tried min="1" and max="2" attributes but user is still able to type 0 manually and form is being submitted.
My project is based on angular 5 and I am using a template driven form. Please do not suggest solutions for reactive forms.
You can try regex also
If you want number in range of 1-2 with 5 decimals without number 2 then use pattern below,
[1]+(.[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?)?
And if you want less than and equal to 2, you can set pattern as,
^(?:2|2.0|2.00|2.000|2.0000|2.00000 | (.[0]{1,2})?|([1])(.[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?)?)$
For example:
<input class="form-control"
[(ngModel)]="data" name="dataModel" #dataModel="ngModel" required
pattern="^(?:([2])(\.[0]*)? | (\.[0]{1,2})?|([1])(\.[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?)?)$">
<div *ngIf="dataModel.errors && (dataModel.dirty || dataModel.touched)">
<small [hidden]="!dataModel.errors.required">
Required
</small>
<small [hidden]="!dataModel.errors.pattern">
pattern check
</small>
</div>
And if you want in range of 0-2 including 2 then you can set pattern as,
^(?:2|2.0|2.00|2.000|2.0000|2.00000 | (.[0]{1,2})?|([0-1])(.[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?)?)$
If you want in range of 0-2 excluding 0 then pattern can be (this pattern accepts from 0.00001 to 2.00000 numbers),
^(2|2.0|2.00|2.000|2.0000|2.00000|([1]+(.?[0-9]?[0-9]?[0-9]?[0-9]?[0-9]?){1}|[0]+(.[0-9]{0,4}[1-9]{1})))$
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments