Created
August 7, 2014 08:38
-
-
Save iambigd/c1cc7460e9af5e35001a to your computer and use it in GitHub Desktop.
Angular Form validation: alphanumeric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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