Skip to content

Instantly share code, notes, and snippets.

@gerasimua
Created July 30, 2015 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerasimua/906497b31d4f8e596361 to your computer and use it in GitHub Desktop.
Save gerasimua/906497b31d4f8e596361 to your computer and use it in GitHub Desktop.
Angular phone number helper
<input type="text" ng-model="user.phone" name="phone" ng-change="numberHelper()" ng-model-options="{allowInvalid:true}" ng-pattern="/^\+\d-\d{3}-\d{3}-\d{4}$/"/>
function numberHelper(){
var phone = $scope.user.phone;
var formattedPhone = phone;
if(phone && !/^\+\d-\d{3}-\d{3}-\d{4}$/.test(phone)){
phone = phone.replace(/[+-]/g, '');
phone = '+' + phone.substr(0, 1)
+ (phone[1] ? '-' : '') + phone.substr(1, 3)
+ (phone[4] ? '-' : '') + phone.substr(4, 3)
+ (phone[7] ? '-' : '') + phone.substr(7, 4);
formattedPhone = phone;
}
$scope.user.phone = formattedPhone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment