简体   繁体   English

无法使用 Angular.js 正确验证字段

[英]Can not validate the field properly using Angular.js

I need to validate properly the input field as per user requirement using AngularJS.我需要根据用户要求使用 AngularJS 正确验证输入字段。

I am providing my code below:我在下面提供我的代码:

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

Here requirement is user can entry number only with + or - like this ie-+123.45 or -095.4567 .这里的要求是用户只能使用+-输入编号,例如- ie-+123.45 or -095.4567 In current case the + or - is not allowed only numbers are allowed.在当前情况下,不允许使用+-只允许使用数字。

您需要在正则表达式中允许相应的符号

ng-pattern="/^(\+|-)?[0-9]+([,.][0-9]+)?$/"

ng-pattern="/^([+|-][[0-9]+([,.][0-9]{n,m}))]?$/"; ng-pattern="/^([+|-][[0-9]+([,.][0-9]{n,m}))]?$/";

try using this just replace n and m with minimum number of decimal places ie in ur case be 0 and m with highest number of decimal places allowed尝试使用这个只是用最小的小数位数替换 n 和 m,即在你的情况下是 0 和 m,允许的小数位数最高

You can write own directive for custom validation like below one.您可以编写自己的自定义验证指令,如下所示。

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-app="app" ng-controller="HomeCtrl">
    <div>
      <form novalidate name="myForm">
        Number: <input type="text" name="valText" ng-model="val" even-number />
      </form>
    </div>
    <div>
      <span style="color: red;" ng-show="myForm.valText.$error.evenNumber">Invalid value</span>
      <br />
      <br />
      <button ng-click="setValue(22)">Change Value to 22</button>
      <br />
      <button ng-click="setValue(19)">Change Value to 19</button>
    </div>
  </body>

</html>

Plunkr .普朗克

This Even Number directive, only even number is allowed.这个偶数指令,只允许偶数。

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

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