Validate Phone Number
by Trisox
HTML
<div ng-controller="Ctrl">
<form name="form" novalidate>
<label>Phone Number</label>
<input type="text" name="phone" data-phone ng-model="phone" />
<span ng-show="form.phone.$error.phoneField">Please enter a valid phone number.</span>
</form>
</div>
JavaScript
var app = angular.module('myApp', []);
var PHONE_REGEXP = /^[(]{0,1}[0-9]{3}[)\.\- ]{0,1}[0-9]{3}[\.\- ]{0,1}[0-9]{4}$/;
app.controller('Ctrl', function($scope) {});
app.directive('phone', function() {
return {
restrice: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
angular.element(element).bind('blur', function() {
var value = this.value;
if(PHONE_REGEXP.test(value)) {
// Valid input
console.log("valid phone number");
angular.element(this).next().next().css('display','none');
} else {
// Invalid input
console.log("invalid phone number");
angular.element(this).next().next().css('display','block');
/*
Looks like at this point ctrl is not available,
so I can't user the following method to display the error node:
ctrl.$setValidity('currencyField', false);
*/
}
});
}
}
});