0

Here I have phone numbers input field and I check this input field phoneNumber in if condition this phone number has only numbers or characters using regex, I check this regex using match but if condition gives error like match is not found, I want to check phoneNumber is only number in if condition how it is possible in angularjs ?

<div class="col-md-6">
   <small>Phone Number</small>
   <input type="text" name="phonenumber" placeholder="" ng-model="phoneNumber">
</div>

 if($scope.phoneNumber.match(/^[0-9]*$/)) {
    factories.error('This is valid phone number');
 } else {
    factories.error('Phone Number must be a number');
 }
5
  • 1
    If phoneNumber is undefined you'll hit an issue, you should use ngPattern on the model. docs.angularjs.org/api/ng/directive/ngPattern Commented Sep 10, 2019 at 13:08
  • @kendavidson but ng-pattern not throws error, ng-pattern only if not valid phoneNumber then it is hide not throws error Commented Sep 10, 2019 at 13:12
  • Ah, my bad. Then just check for phoneNumber being undefined before using it? You can take a look at the ui-validate module as well, you can do both validate and use your .error() function in one shot. Commented Sep 10, 2019 at 13:15
  • Is this not any way to check validation for any country phone number in if condition in angularjs ? Commented Sep 10, 2019 at 13:27
  • I'm confused by your last comment. There are really limited options a) ngPattern b) ui-validate module with function c) $watch phoneNumber d) some key/change event. Regardless, you need to check phoneNumber for undefined before calling .match() on it. Commented Sep 10, 2019 at 16:54

1 Answer 1

1

You can use the ngPattern directive with a html form element;

Pattern for 10 digit phone number :

ng-pattern="/^[0-9]{10}$/"

see jsfiddle for an example. https://jsfiddle.net/3p6daLbv/

You can also add dynamic errors using ng-messages and ng-message-exp directives;

      <div ng-messages="myForm.tel.$error" role="alert">
          <div ng-message-exp="['pattern']">
            Your number must be 10 numbers long.
          </div>
      </div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.