简体   繁体   中英

Can not validate the field properly using Angular.js

I need to validate properly the input field as per user requirement using 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 . 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}))]?$/";

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

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.

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