Skip to content

Instantly share code, notes, and snippets.

@MeTe-30
Last active November 28, 2016 10:06
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 MeTe-30/360591f72512d4add560419cf7559892 to your computer and use it in GitHub Desktop.
Save MeTe-30/360591f72512d4add560419cf7559892 to your computer and use it in GitHub Desktop.
Add custom validation to ngModel (useful in forms) | AngularJs
app.directive('ngValidation', function () {
return {
require: 'ngModel',
scope: {
ngValidation: '='
},
link: function (scope, element, attrs, ngModel) {
scope.$watch('ngValidation', function (newVal) {
if (!(newVal instanceof Object)) return;
if (!(newVal instanceof Array)) newVal = [newVal];
angular.forEach(newVal, function (item) {
ngModel.$setValidity(item.name, item.value);
});
}, true);
}
}
});
-------------------
UseCase:
<form name="frm">
<input type="number" name="number" ng-model="model" required ng-validation="[{name: 'byTwo', value: model%2==0}, {name: 'byFive', value: model%5==0}]" />
<div ng-messages="frm.number.$error" multiple>
<div ng-message="required">input is required !!</div>
<div ng-message="byTwo">input is not divisible by 2 !!</div>
<div ng-message="byFive">input is not divisible by 5 !!</div>
</div>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment