1

Update : So i changed the input to type = "text" and maxlength is working fine but user is still able to enter negative numbers and is able to enter numbers not lying in the min and max range.

I need to validate an input field of type number in such a way that its min value should be 1.1, max value should be 8.1 and only 1 decimal value should be allowed. I am using template driven forms but user is still able to input a value greater than 8.1, less than 1.1 and he is able to enter more than one decimal place digit (i need help validating this logic as well). My requirement is to not let user be able to click the save button if any of the logic fails.

For allowing only one value after decimal requirement, i tried using maxlength but it does not work.

I tried using the below logic:

Component.html

<input type="number" min= "1.1" max ="8.1" #c="ngModel" [ngModel]= "myvaluefromcomponent | number:'1.1-1'" (ngModel)="myvaluefromcomponet=$event" />

<button type="button" id="save" [disabled] ="c.errors"> Save </button>

This is not working properly. Please point out where i am going wrong and suggest a working solution for this problem. Thanks

3
  • 1
    use ng-pattern and add regex to do the validation Commented Sep 21, 2018 at 4:07
  • i think it might work. I will check it. Could you also check from your end if it works? Commented Sep 21, 2018 at 4:24
  • @PramodPatil : ng-pattern is not applicable in angular 5. Probably it would have been used in angularjs. Thanks for the pointer though, it directed me to the right solution :) Commented Sep 26, 2018 at 10:23

1 Answer 1

3

I came across the PatternValidator directive and it solved my problem. I can use the directive on any control in this way :

<input type="number" min= "1.1" max ="8.1" #c="ngModel" [pattern]="myPattern" [ngModel]= "myvaluefromcomponent"/>

<button type="button" id="save" [disabled] ="c.errors?.pattern"> Save </button>

Hope the same works for other users looking for this kind of an implementation

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

Comments

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.