I have created my own conditional validation attribute to validate my MVC model on both the client and the server by inheriting from RequiredAttribute
and implementing IClientValidatable
. The idea is that if a boolean property on my model is true, then another property is required. In the view this manifests itself as a checkbox which dictates whether a textbox needs to be filled in.
This works perfect except for when the user performs the following actions:
I would like to revalidate the form when the checkbox is checked or unchecked, or even better just revalidate that field, so that the error message is no longer displayed. I have tried various combinations of calling the jQuery validate()
method, but nothing seems to be able to re-run validation.
I use the following javascript to set up my validation function and the associated unobtrusive adapter.
$.validator.addMethod(
"requiredif",
function(value, element, parameters) {
var selector = "#" + parameters["dependentpropertyname"];
var triggerValue = parameters["triggervalue"].toString().toLowerCase();
var actualValue = $(selector).is(":checked").toString().toLowerCase();
if (actualValue === triggerValue) return $.validator.methods.required.call(this, value, element, parameters);
return true;
});
$.validator.unobtrusive.adapters.add(
"requiredif",
["dependentpropertyname", "triggervalue"],
function(options) {
options.rules["requiredif"] = {
dependentpropertyname: options.params["dependentpropertyname"],
triggervalue: options.params["triggervalue"]
};
options.messages["requiredif"] = options.message;
}
);
Thanks!
Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. data-val-required=”This is required.”
validator. unobtrusive. parse(selector) method to force parsing. This method parses all the HTML elements in the specified selector and looks for input elements decorated with the [data-val=true] attribute value and enables validation according to the data-val-* attribute values.
validator. addMethod( name, method [, message ] ) Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.
I had a similar problem where I wanted to revalidate a datepicker field using jquery validate and jquery ui. This post helped me figure it out.
The key, is just add a callback to the valid method for that selector. Something like:
$(".requiredif").change(function() {
$(this).valid();
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With