Search code examples
regexangularjspugng-pattern

How to get use ng-pattern


I have a simple text input in which I only want to allow floats and ints (watch out: jade)

input.form-control(type="text", ng-model='usd', ng-pattern="nums",ng-change='convert_to_btc()', placeholder="USD")

However it doesn't work, I can always insert any character in the input (do I need to do more in order to display something? e.g. a red border if it's incorrrect? or should then just those characters not even be able to be entered?) The pattern is a regex and thus not a string, so that should be fine???

Here's the controller:

app.controller("AppCtrl", function AppCtrl($scope, $http, $interval ) {
    //lots of other stuff
    $scope.nums = /^\-?\d+((\.|\,)\d+)?$/; //note no string, it's a  regex
}

This is the generated HTML. Could this be the problem? The generated HTML actually has a string, not a regex!?

<input type="text" ng-model="usd" ng-pattern="/^\-?\d+((\.|\,)\d+)?$/" ng-change="convert_to_btc()" placeholder="USD" class="form-control ng-dirty ng-valid-parse ng-touched ng-invalid ng-invalid-pattern">

Solution

  • I hope this is what you are trying to do.

    Please have a look at the below link

    http://plnkr.co/edit/BGzLbQHy0ZtHYmom8xA3

    <!DOCTYPE html>
    <html ng-app="">
    
    <head>
     <script data-require="[email protected]" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13">      
     </script>
      <style>
        .ng-invalid-pattern {
          border:1px solid #f00;
        }
      </style>
    </head>
    
    <body>
      <p>Hello</p>
    
      <form name='myform'>      
        <input type="text" name='ip' ng-model="usd" ng-pattern="/^\-?\d+((\.|\,)\d+)?$/" 
      ng-change="convert_to_btc()" placeholder="USD"/>
        <p ng-show='myform.ip.$invalid'>Error</p>
      </form>
    
    
      </body>
    
    </html>