What is the correct way to override the ErrorPlacement function in jquery.validate.unobtrusive?
Looking at the jquery.validate.unobtrusive.js script, it looks like the intention of the developers will allow you to apply your own ErrorPlacement function by setting $ jQval.unobtrusive.options.
In the validationInfo (form) function, which defines the errorPlacement function, we see a call to execInContext ("errorPlacement", arguments).
It would seem that if we create the errorPlacement function under $ .validator.unobtrusive.options, then this will be called.
$.validator.unobtrusive.options = { errorPlacement: function () { console.log("hello"); } };
The problem is that it has to be configured after jquery.validate.js and before jquery.validate.unobtrusive.js is specified. Otherwise, $ jQval.unobtrusive.options is null and $ form.data (data_validation, result) will no longer be set.
function validationInfo(form) { var $form = $(form), result = $form.data(data_validation), onResetProxy = $.proxy(onReset, form), defaultOptions = $jQval.unobtrusive.options || {}, execInContext = function (name, args) { var func = defaultOptions[name]; func && $.isFunction(func) && func.apply(form, args); } if (!result) { result = { options: { // options structure passed to jQuery Validate validate() method errorClass: defaultOptions.errorClass || "input-validation-error", errorElement: defaultOptions.errorElement || "span", errorPlacement: function () { onError.apply(form, arguments); execInContext("errorPlacement", arguments); }, invalidHandler: function () { onErrors.apply(form, arguments); execInContext("invalidHandler", arguments); }, messages: {}, rules: {}, success: function () { onSuccess.apply(form, arguments); execInContext("success", arguments); } }, attachValidation: function () { $form .off("reset." + data_validation, onResetProxy) .on("reset." + data_validation, onResetProxy) .validate(this.options); }, validate: function () { // a validation function that is called by unobtrusive Ajax $form.validate(); return $form.valid(); } }; $form.data(data_validation, result); } return result; }
Another way to handle this is
set the error $ .validator.unobtrusive.options. Placement function
remove unobtrusive check
apply unobtrusive check
$.validator.unobtrusive.options = { errorPlacement: function () { console.log("errorPlacement"); } }; $("#form_selector").removeData("unobtrusiveValidation");
Or another option is to override the function call.
var validator = $("#form_selector").data('validator'); var originalFunction = validator.settings.errorPlacement; validator.settings.errorPlacement = function(error,element) { console.log("errorPlacement"); originalFunction(error, element); };
What is the correct way to implement my own errorPlacement method?