Skip to content

Instantly share code, notes, and snippets.

@ohsiwon
Last active June 3, 2016 18:38
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 ohsiwon/61b7f9b57a8f2f7ba8f36be1d3ea2dd5 to your computer and use it in GitHub Desktop.
Save ohsiwon/61b7f9b57a8f2f7ba8f36be1d3ea2dd5 to your computer and use it in GitHub Desktop.
AngularJs input validator directive for text, email and U.S. phone number
(function() {
'use strict';
function inputValidator($log) {
var vm, directive, inputType, regex;
function link(scope, element, attrs, ngModel) {
vm = scope;
function init() {
regex = {
text : /^[a-zA-Z][a-zA-Z0-9]+$/,
email : /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i,
phone : /^[0-9]+$/
};
ngModel.$parsers.push(validate);
};
function validate(ngModelValue) {
inputType = attrs.ngType || attrs.type;
// Custom name validation (value must start with letter)
if(inputType === 'name') ngModel.$setValidity('invalidName', regex.text.test(ngModelValue));
// Custom Email validation (*preloaded Angular email validation is passing true value w/o domain extension)
if(inputType === 'email') ngModel.$setValidity('invalidEmail', regex.email.test(ngModelValue));
// Custom Phone # validation (Prevent non-numeric character)
if(inputType === 'phone') {
var number, formattedNumber, area, front, end;
// Strip out letter first
formattedNumber = number = String(ngModelValue.replace(/[^0-9]/g, ''));
// Also if the first character is '1', strip it out and add it back
number = number[0] == '1' ? number.slice(1) : number;
// Mask (###) ###-####
area = number.substring(0,3);
front = number.substring(3, 6);
end = number.substring(6, 10);
if (front) formattedNumber = ("(" + area + ") " + front);
if (end) formattedNumber += ("-" + end);
ngModel.$setViewValue(formattedNumber);
// Send validity (it get you trouble when masked length isn't 14)
if(formattedNumber.length != 14) ngModel.$setValidity('invalidPhone', false);
else ngModel.$setValidity('invalidPhone', true);
ngModel.$render();
}
return ngModelValue;
}
init();
}
directive = {
link: link,
restrict: 'A',
require: 'ngModel',
scope: {}
};
return directive;
}
inputValidator.$inject = ['$log'];
angular
.module('reserveApp')
.directive('inputValidator', inputValidator);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment