ng-required does not work with number input with min condition

363 views Asked by At

I have a checkbox, based on value of its ng-model, I'm toggling visibility of a div using ng-show.

This div contains an <input> of type="number". I have a validation on it of min="10000".

I dont want the form to get submitted if the number input is less than 10000. However, I want this only to happen when the checkbox is checked. So, I'm using ng-required to check the value of checkbox.

<input type="checkbox" ng-model="isOn"/>

<div ng-show="isOn">
    <input type="number" min="10000" ng-model="counter" ng-required="isOn"/>
</div>

If someone proceeds without touching the checkbox and the input field, the form get submitted. However, if I click the checkbox, enter a number<10000, and the uncheck it again, the form doesn't get submitted.

On the console I get error that it cannot focus on the the input control. The ng-required fails to work on the min condition. It is being checked regardless of ng-required.

Is there any way I can get this working?

PS: I dont want to use the solution with text input + length limit + restricted char codes on key press so that only numbers could be typed.

3

There are 3 answers

0
Dushyant Bangal On BEST ANSWER

I used ng-if instead of ng-show and it worked.

I had tried it before I posted the question, but it didnt work. Later I realized I had done the change on a different html file.

0
Jazib On

you need to reset the model of the number input field to its initial state as well when user unchecks the checkbox.

0
Praveen Kumar On

I hope this should work

<form name="MyForm" novalidate >
<input type="checkbox" ng-model="MyForm.isOn" required/>
 <div ng-show="MyForm.isOn.$touched||MyForm.$submitted">
 <span class="errormsg" ng-message="required" ng-show="MyForm.counter.$error.required">Please select the checkbox</span>                                                        
 </div>                 
<div ng-show="MyForm.isOn">
<input type="text"  ng-model="MyForm.counter" required min="1000" />
 <div ng-show="MyForm.counter.$touched||MyForm.$submitted">
 <span class="errormsg" ng-message="required" ng-show="MyForm.counter.$error.required">You can't leave this empty</span>                       
  <span class="errormsg" ng-message="required" ng-show="MyForm.counter.$error.min">Value should be atleast 1000</span>                        
  </div>
 </div>
 </form>