AngularJS : email or phone number validation

Rohit Jindal picture Rohit Jindal · Dec 29, 2016 · Viewed 13.3k times · Source

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 :

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

Answer

Saidulu Buchhala picture Saidulu Buchhala · Apr 12, 2017

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>