How to use regex in angularjs

I have tried this code.

<script>
  angular.module('emailExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.text = 'me@example.com';
    }]);
</script>
  <form name="myForm" ng-controller="ExampleController">
    Email: <input type="email" name="input" ng-model="text" required>
    <span class="error" ng-show="myForm.input.$error.required">
      Required!</span>
    <span class="error" ng-show="myForm.input.$error.email">
      Not valid email!</span>
    <tt>text = {{text}}</tt><br/>
    <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
    <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
    <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
    <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
    <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  </form>

      

But the problem is verification. Let's say if I try to type ' a @ ac ' into email then it doesn't show any errors. Please help me with this.

+3


source to share


1 answer


I think why you don't use ng-pattern

for this. You can make a regex and insert insideng-pattern.

Example:

<form name="signupFrm">

    <input type="email", ng-pattern="emailPattern">

</form>

      

or,



HTML:

    <div ng-class="{'has-error': signupFrm.email.$dirty && signupFrm.email.$invalid}">
        <input type="email" placeholder="Email" name="email" ng-pattern="emailPattern" required="required">
        <div ng-show="signupFrm.email.$dirty && signupFrm.email.$invalid || signupFrm.email.$error.pattern">
           <span ng-show="signupFrm.email.$error.pattern && signupFrm.email.$invalid " class="help-block"> should look like an email address</span>
           <span ng-show=" signupFrm.email.$error.required" class="help-block">can't be blank</span>
       </div> 
  </div>

      

JS:

$scope.emailPattern = /^([a-zA-Z0-9])+([a-zA-Z0-9._%+-])+@([a-zA-Z0-9_.-])+\.(([a-zA-Z]){2,6})$/;

      

+8


source







All Articles