Using ng-pattern to validate email in AngularJS

Afshin Ghazi picture Afshin Ghazi · Feb 11, 2016 · Viewed 25.8k times · Source

I'm new to Angular and have trouble getting the ng-pattern to validate the email address based on a REGEX. In fact the other default angular validation for email also changes behaviour and only shows an error if the entire field is empty when I insert ng-pattern. Initially tried using directives and controllers but found that the ng-pattern can achieve (in theory) the same effect of validating the email so decided to use this.

I have used several REGEX patterns and read about ng-pattern such as from: Regex validation of ng-patternForm validationEasy form validation and many other links but nothing works. Can anybody figure-out what I need to do to make things work ?

  <form name="userForm" novalidate>
    <div class="row">
                    <div class="large-12 medium-12 small-12 columns">
                        <label>Username</label>
                            <input type="email" name="username" placeholder="[email protected]" ng-model="user.username" ng-maxlength="100" ng-model-options="{ updateOn: blur }" ng-pattern = "/^(?("")("".+?(?<!\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'*\+/=\?\^`\{\}\|~\w])*)(‌​?<=[0-9a-z])@))(?([)([(\d{1,3}\.){3}\d{1,3}])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-‌​z0-9][\-a-z0-9]{0,22}[a-z0-9]))$/" required />
                            <div class="error-container" ng-show="userForm.username.$dirty && userForm.username.$invalid">
                              <small class="error" ng-show="userForm.username.$error.required">
                                     Your email is required.
                              </small>
                              <small class="error" ng-show="userForm.username.$error.email">
                                     Please input a valid email.
                              </small>
                              <small class="error" ng-show="userForm.firstname.$error.maxlength">
                                    Your email cannot be longer than 100 characters
                              </small>                        
                            </div>
                    </div>
</form>

Answer

ashfaq.p picture ashfaq.p · Feb 11, 2016

Please change your ng-pattern to match this regex:

ng-pattern = '/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i'

This regex will give error if the section after @ is left blank. This regex will accept unicode also.

Hope it helps.