How to manually revalidate / trigger validation using unobtrusive jQuery validation?
Asked Answered
K

2

11

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:

  • Checks the checkbox (the field is now required).
  • Submits the form (client side validation runs, error message displayed).
  • User unchecks box (error message remains, field no longer required).

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!

Kingly answered 18/7, 2012 at 2:56 Comment(0)
T
19

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();
})
Trivium answered 11/10, 2012 at 19:39 Comment(0)
R
-5

You should check out Foolproof Validation. It does what you are trying to do without you having to roll your own.

Rileyrilievo answered 18/7, 2012 at 14:55 Comment(2)
That looks great! Thanks for the link, but I still have the same problem. I.e. how to revalidate/trigger validation on the client for all or part of my form?Kingly
This does not answer the question. The OP has asked how to peel and orange and you've answered by saying you should eat an apple instead. Could possibly be a comment.Etymologize

© 2022 - 2024 — McMap. All rights reserved.