ralcazar ralcazar - 28 days ago 8
AngularJS Question

How will I disallow specific characters in AngularJS Regular Expression?

I tried this to disallow characters

<input type="text" id="full_name" name="full_name" ng-pattern="/[^\@\-#\-&]/">


but it's not working.

Answer Source

If you want to disallow @, #, &, and - characters, use "/^[^@#&-]*$/":

<input type="text" id="full_name" name="full_name" ng-model="YOUR_MODEL" ng-pattern="/^[^@#&-]*$/" />

The ^[^@#&-]*$ pattern matches:

  • ^ - start of string
  • [^@#&-]* - 0 or more chars other than the ones defined in the negated character class
  • $ - end of string.

Note: to make the value required, you may add required attribute, or replace the * quantifier in the pattern with + (to require at least 1 (or more) characters).

var myApp = angular.module('myApp', []);
function func($scope){
}
<html ng-app="myApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js">    </script>
</head>

<body ng-controller="func">
<form name="myForm" ng-submit="onSubmit()">
    <input type="text" id="full_name" name="full_name" ng-model="myApp" ng-pattern="/^[^@#&-]*$/" required/>
    <span ng-show="myForm.full_name.$error.pattern">Not valid</span>
  </form>
</body>
</html>