Skip to content

Instantly share code, notes, and snippets.

@Archakov06
Last active October 30, 2016 16:05
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 Archakov06/b168fe585b50e4fc7ba1003caccafa86 to your computer and use it in GitHub Desktop.
Save Archakov06/b168fe585b50e4fc7ba1003caccafa86 to your computer and use it in GitHub Desktop.
app.directive('validex', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (val) {
if (!attrs.validex) return false;
var pattern = attrs.validex;
var flags = attrs.vflags ? attrs.vflags : '';
var exp = new RegExp(pattern,flags);
switch (pattern) {
case 'email':
exp = /[A-Z0-9._%+-]+@[A-Z0-9-]+.+.[A-Z]{2,4}/igm;
break;
case 'url':
exp = /https?:\/\/(?:[-\w]+\.)?([-\w]+)\.\w+(?:\.\w+)?\/?.*/i;
break;
case 'phone':
exp = /^\+?[2-9]\d{2}[0-9]\d{3}\d{4}$/;
break;
case 'tw-username':
exp = /^@([A-Za-z0-9_]{3,15})$/;
break;
case 'card':
exp = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/;
break;
case 'hex':
exp = /\#([a-fA-F]|[0-9]){3, 6}/;
break;
default:
exp = new RegExp(pattern,flags);
break;
}
if (val.match(exp))
{
element.removeClass('error');
scope.status = 'ok';
}
else {
element.addClass('error');
scope.status = 'error!';
}
});
}
};
});
// Use Twitter username (Example: @username): <input validex validex="^@([A-Za-z0-9_]{3,15})$" type="text">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment