AngularJS : email or phone number validation

14.4k Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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>

1
On

You could use angular form validators among with the ng-pattern directive.

<form name="userForm">
    <input type="text" name="emailphone" ng-model="userData.user" id="emailphone" ng-pattern="/(^[0-9]{10,10}$)|(^[a-z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+))?$/" />
    <button type="submit" ng-disabled="userForm.$invalid" ng-click="validate()">Submit</button>
</form>

Once you name your form you are able to use the validators from it. userForm.$invalid will be true in case it detects an invalid input inside the form. Then, with the directive ng-disabled you could disable the button.

Since we added the ng-pattetrn, it will be true unless the input match the ng-pattern regular expression.

Another thing to know is that the ng-model value: userData.user will be undefined unless it matches the regular expression

7
On

Do this, we can use NgFormControllers and validators to validate a form in angularjs. Below code helps you to enter correct email or phone while typing and before submitting the form. ng-if="form.emailphone.$error.pattern" in this, form is name of the form and emailphone is the name of the input field and $error is the holder of failed validations. $error.pattern will be true until the input matches the expression in the ng-pattern

<form name="form">
     <input type="text" name="emailphone" ng-model="email" ng-pattern="/^([a-z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?)|[7-9][0-9]{9}$/" >
     <span ng-if="form.emailphone.$error.pattern">Enter correct email or phone number!</span>
</form>

ng-model is mandatory. Otherwise it won't work. Because it is undefined until the pattern matches. As you know, validate forms before submitting them for better user experience