I need to create a validation directive for showing all input errors for each input automatically. This validation directive should show all errors at current moment and list of
Here is the pattern that I used (with Angular 1.3):
app.directive('number', function() {
var NUMBER_REGEXP = /^(\d+)$/;
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.number = function(modelValue, viewValue) {
return NUMBER_REGEXP.test(viewValue);
};
}
};
});
Then I was able to check for errors in the HTML (with Bootstrap 3.3) using this pattern:
Explanation:
The number
attribute in the tag triggers the directive, which causes the
ngModel
validator 'number'
to be called and to set/unset value.$error.number
.
If value.$error.number
is set, then the has-error
class is applied to the form-group
so it displays a red input field and the help message is displayed.