4

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

Community
  • 1
  • 1
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • https://codepen.io/rpdasilva/pen/DpbFf My favorite phone directive. Not perfectly applicable in your case, but it might help to take a look. – StephanieQ Dec 29 '16 at 19:47
  • What did you find is "not working per [your] expectation" in that other question's answers? Because that's pretty close to an exact duplicate of this question. – Heretic Monkey Dec 29 '16 at 21:12
  • @MikeMcCaughan validation not working as per my expectation. When i am trying to type alphabet it shows me a wrong error message that phone number is not valid as i am trying to input email. – Debug Diva Dec 30 '16 at 03:28
  • If you want validation on keystroke, it won't know if you're entering a email or a phone number. Add `ng-model-options="{ 'updateOn': 'blur' }"` if you want validation to occur when they leave the field. – Heretic Monkey Dec 30 '16 at 15:26

3 Answers3

4

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>
S B
  • 1,363
  • 12
  • 21
1

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

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62
  • Please read my question again. I need to validate the Email/Phone in single text-box not only Email. – Debug Diva Dec 30 '16 at 06:59
  • Just write the correct pattern for both. That's it. I also mentioned in the answer – Mr_Perfect Dec 30 '16 at 07:08
  • Can you please provide fiddle link.In your answer i am only able to email validation message. How it will work with Phone. – Debug Diva Dec 30 '16 at 07:55
  • Now my question is how i will display the seperate error message for mobile and email with same ng-pattern ? – Debug Diva Jan 05 '17 at 08:44
  • I dont know why you want to display two messages for single input. Just try to display `enter correct email or phone number`. Or you can have a name that refer both like, `username` – Mr_Perfect Jan 05 '17 at 08:47
  • But if user type number like "9" . it would be a number or email also. So, how it will be distinguish ?. i dont want to display any error message when user type any numeric or alphanumeric digit on first index – Debug Diva Jan 05 '17 at 08:49
  • a email never start with a number. – Mr_Perfect Jan 05 '17 at 08:52
0

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

Manu Obre
  • 2,254
  • 1
  • 12
  • 12