Search code examples
angularjsvalidationng-pattern

AngularJS : email or phone number validation


Expectation :

I am working on login form in Angular. Users can login with Email/Phone. I need to validate the Email/Phone in single text-box.

Live Scenario :

Facebook implemented same type of functionality in login. we can login in Facebook via Email/Phone. But as per the research Facebook validates the user data by performing server side validations not the client side validations.

Tried so far :

function validate() {
  var textBoxValue = document.getElementById('emailphone').value;
  var emailPattern = /^[a-z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/; 
  if(textBoxValue == '') {
    alert('Please enter value');
    return false;
  } else if(isNaN(textBoxValue)) {
    if(!(textBoxValue.match(emailPattern))) {
      alert('Please enter valid email');
      return false;
    }
  } else {
    if(textBoxValue.length != 10) {
      alert('Please enter valid phno');
      return false;
    }
  }
}
<input type="text" name="emailphone" id="emailphone"/>
<input type="submit" value="Validate" onclick="validate()">

I am able to achieve this functionality using pure JavaScript but I want to implement it in Angular using ng-pattern or if there is any work around in Angular.

I found this post on SO but not working as per my expectation.

Validation for email or phone number for same text field in angularjs


Solution

  • You can use angular form validation and ng-pattern directive for input use ng-pattern="/^(?:\d{10}|\w+@\w+\.\w{2,3})$/"

    Working Demo

    var app = angular.module("MY_APP", []);
    app.controller("MyCtrl", function($scope) {
      $scope.submitted = false;
      $scope.submit = function(userData){
      	console.log(userData)
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="MY_APP">
      <div ng-controller="MyCtrl">
      <form name="userForm" novalidate ng-submit="userForm.$valid && submit(userData)">
                  <div class="errorMsg" ng-show="submitted==true && userForm.$invalid">
                        <ul>
                            <li ng-show="submitted==true && userForm.emailphone.$error" class="errorMsg">
                                wrong format, It should be email or 10 digit mobile number
                            </li>
                        </ul>
                    </div>
        <input type="text" name="emailphone" ng-model="userData.user" id="emailphone"  required
        ng-pattern="/^(?:\d{10}|\w+@\w+\.\w{2,3})$/" />
        <button type="submit" ng-click="submitted = true">Submit</button>
    </form>
    </div>
    </div>