简体   繁体   中英

How to keep + and - in ng-pattern using Angular.js

I need one help. I have one text field which should not take the alpha numerical value but take numbers,+,-,. using Angular.js . I am explaining my code below.

<div ng-class="{ 'myError': billdata.lati.$touched && billdata.lati.$invalid }">
<input type="text" name="lati" id="latitude" class="form-control oditek-form" placeholder="Add Latitude coordinate" ng-model="latitude"   ng-keypress="clearField('businessno');" ng-pattern="/^[0-9]+([,.][0-9]+)?$/">
</div>

But here problem is while this field has value like -122.32379000000003 ,its showing the error message.here i need this field only can accept numbers,+,- and . white space are also not allowed with alphanumerical value. Please help me.

使用/^[.+-]?[0-9]+([,.][0-9]+)?$/

To meet the requirement , you can use the below pattern

ng-pattern="/^[0-9]{1,7}$/"

Example:

<div ng-class="{ 'myError': billdata.lati.$touched && billdata.lati.$invalid }">
<input type="text" name="lati" id="latitude" class="form-control oditek-form" placeholder="Add Latitude coordinate" ng-model="latitude"   ng-keypress="clearField('businessno');" ng-pattern="/^[0-9]{1,7}$/">
</div>

Hope this helps you.

Change you ng-pattern regex to ng-pattern="/^([\\-\\+0-9]{0,1})(\\.?[0-9])*$/"

where ^([\\-\\+0-9]{0,1}) which allows +,- or numbers as a first character

    <form name="myForm">
        <div ng-class="{ 'myError': billdata.lati.$touched && billdata.lati.$invalid }">
          <input type="text" ng-pattern="/^([\-\+0-9]{0,1})(\.?[0-9])*$/" name="lati" id="latitude" class="form-control oditek-form" placeholder="Add Latitude coordinate" ng-model="latitude" ng-keypress="clearField('businessno');" >
      </div>
      <label ng-show="myForm.lati.$error.pattern">Error</label>
  </form>

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