简体   繁体   English

无法使用Angular.js验证输入字段

[英]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. 我在使用Angular.js验证输入字段时遇到问题。我需要输入字段仅输入数字( ie-0,1... -0,1 ie-0,1... ),并且不允许使用任何字符。我在下面解释我的代码。

<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 将输入容器更改为form标签
  • Give a name to the form tag eg name='form' 给表单标签起个名字,例如name='form'
  • Change the myError condition to !form.$valid 将myError条件更改为!form.$valid
  • Change the regex to /^(\\s*|\\d+)$/ to allow empty string or numbers. 将正则表达式更改为/^(\\s*|\\d+)$/以允许使用空字符串或数字。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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