Skip to content

Instantly share code, notes, and snippets.

@iambigd
Created August 7, 2014 08:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iambigd/c1cc7460e9af5e35001a to your computer and use it in GitHub Desktop.
Save iambigd/c1cc7460e9af5e35001a to your computer and use it in GitHub Desktop.
Angular Form validation: alphanumeric
.directive('alphanumeric', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, elem, attr, ngModel) {
var validator = function(value) {
if (/^[a-zA-Z0-9]*$/.test(value)) {
ngModel.$setValidity('alphanumeric', true);
return value;
} else {
//注意得是若驗證沒通過建議回傳undefined
ngModel.$setValidity('alphanumeric', false);
return undefined;
}
};
//For DOM -> model validation
ngModel.$parsers.unshift(validator);
//For model -> DOM validation
ngModel.$formatters.unshift(validator);
}
};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment