简体   繁体   中英

Can not validate input field using Angular.js

I have an issue while validating input field using Angular.js.I need my input field only take numbers( ie-0,1... ) and no characters will be allowed.I am explaining my code below.

<div ng-class="{ 'myError': billdata.dis.$touched && billdata.dis.$invalid }">
<input type="text" name="dis" id="discount" class="form-control" placeholder="Add discount" ng-model="discount" ng-keypress="clearField('discount');" ng-keyup="setLatestSalePrice();" ng-pattern="/^[0-9]$/">
</div>
</div>
<div class="help-block" ng-messages="billdata.dis.$error" ng-if="billdata.dis.$touched">
<p ng-message="pattern" style="color:#F00;">This field needs only number(e.g-0,1..9).</p>
</div>

Here when i am typing the numbers the validation error message is also displaying.Please help me to resolve this issue.

A couple changes

  • Change the input container to a form tag
  • Give a name to the form tag eg name='form'
  • Change the myError condition to !form.$valid
  • Change the regex to /^(\\s*|\\d+)$/ to allow empty string or numbers.

codepen http://codepen.io/Anthonyzou/pen/XXaBdy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM