I have used jQuery Validate's handy addClassRules function to apply a rule to all elements of a given class rather than relying on the elements' name
attribute values. In using the Angular wrapper of jQuery Validate, I've found that the addClassRules
function is not supported out of the box. I tried modifying angular-validate.js
to bring in this functionality, but no luck. The file is small, so I'll paste the whole thing, with my modification, below. Skip to the TL;DR at the end if you prefer.
angular-validate.js (with one modification)
(function (angular, $) {
angular.module('ngValidate', [])
.directive('ngValidate', function () {
return {
require: 'form',
restrict: 'A',
scope: {
ngValidate: '='
},
link: function (scope, element, attrs, form) {
var validator = element.validate(scope.ngValidate);
form.validate = function (options) {
var oldSettings = validator.settings;
validator.settings = $.extend(true, {}, validator.settings, options);
var valid = validator.form();
validator.settings = oldSettings; // Reset to old settings
return valid;
};
form.numberOfInvalids = function () {
return validator.numberOfInvalids();
};
}
};
})
.provider('$validator', function () {
$.validator.setDefaults({
onsubmit: false // to prevent validating twice
});
return {
setDefaults: $.validator.setDefaults,
addMethod: $.validator.addMethod,
addClassRules: $.validator.addClassRules, /*<< this is the line I added >>*/
setDefaultMessages: function (messages) {
angular.extend($.validator.messages, messages);
},
format: $.validator.format,
$get: function () {
return {};
}
};
});
}(angular, jQuery));
I only get an error if I actually try to invoke the addClassRules
function in code. For example:
angular.module("PageModule", ['ngValidate'])
.config(function($validatorProvider) {
$validatorProvider.setDefaults({
errorClass: "error custom-error-class" // this works fine
})
$validatorProvider.addMethod("customValidationMethod", function (value) {
var isValid = false;
// do stuff
return isValid;
}, "Bleh"
); // this works fine too
$validatorProvider.addClassRules("emailField", {
email: true
}); // this crashes :(
});
And the error is as follows:
Is there a way for me to use jQuery Validate's addClassRules
function within its Angular implementation? What modification might I need to make? Or, is there a better way to apply validation rules to multiple elements on something other than the name
attribute?