AngularJS 1.4 mask input for phone number issues

566 Views Asked by At

I'm fairly new to dev work and i've run into an issue. supporting an app and they want to do masking on the input for a phone number. They want to have the input be that you can only enter a phone number in a xxx-xxx-xxxx format. Currently we are checking input, but only when we write to the DB.

The app has no masking built into it and is using AngularJS 1.4.9. I was able to locate something at the below URL however I'm having issues with it not working. I can call mask in my html template but it doesn't seem to do anything.

Does anyone have any suggestions or something that is easy to implement? I don't want to re-write a ton of the app. Right now we do the validation on the write to the DB, which can be annoying as you dont get the error till you hit save and then you lost all the data you put into the form.

I'm also very new to Angular, sorry for any misunderstandings i might have.

https://github.com/candreoliveira/ngMask

1

There are 1 best solutions below

2
On

You can do that without installing any new dependencies using ng-pattern, running link

 <ng-form name="myForm" ng-controller="mainCtrl">
<div>Phone No. :</div>
<div>
  <input type="text" placeholder="913-636-7865" name="phone" ng-pattern="phoneNumbr" ng-model="phone" />
  <span class="error" ng-show="myForm.phone.$error.required">Required!</span>
  <span class="error" ng-show="myForm.phone.$error.minlength">Phone no not less that 10 char.</span>
  <span class="error" ng-show="myForm.phone.$error.maxlength">Phone no not more than 11 char.</span>
  <br><span class="error" ng-show="myForm.phone.$error.pattern">Please match pattern [913-636-7865]</span>
</div>

Using ng-mask is a good option , but make sure you have it installed and added to your dependency list

angular.module('yourApp', ['ngMask']);

here what should your html look like :

<div class="row">
                    <div class="col-md-6">
                        <label>Phone number (Home)</label>
                        <input type="tel"
                               name="phone"
                               mask="999-999-9999"
                               ng-model="phone"/>
                      
                    </div>