Anil Kumar
Anil Kumar

Reputation: 229

How to use regular expression in angularjs

I have tried this code..

<script>
  angular.module('emailExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.text = '[email protected]';
    }]);
</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 getting issue in validation. Say if i try to enter '[email protected]' in email then it will not show any error. Please help me on this.

Upvotes: 3

Views: 42049

Answers (1)

Ved
Ved

Reputation: 12113

I am thinking why you are not using ng-pattern for this. You can make a regular expression and put inside ng-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})$/;

Upvotes: 8

Related Questions