Tesserex
Tesserex

Reputation: 17314

Trying to add required to jQuery validation ruins everything else

I've read every other jQuery validation question I could find and nothing is helping me. I'm trying to do something that should be so simple but unobtrusive validation makes me want to punch a hole in my all four of my monitors (jealous?)

I have one field in the form of a select, and another as a date picker. When the select takes on a certain value, the date becomes required. For all other select values, the date is optional. When the page first loads, the date is optional - that is, there is no Required attribute in the model metadata.

Here is my script block along with holes for what I need help with:

<script type="text/javascript">
    function DateRequirement() {
        if ($("#StatusID").val() == 602) {
            $("#DateOfFirstCoverage").attr("data-val-required", "A date is required for current members.");
            // some kind of re-validating here?
        }
        else if ($("#DateOfFirstCoverage").attr("data-val-required") !== undefined) {
            $("#DateOfFirstCoverage").rules("remove", "required");
            // some kind of re-validating here?
        }
    }

    $("#StatusID").change(DateRequirement);
    $(document).ready(DateRequirement);
</script>

Just FYI I have tried other ways of adding the requirement, such as using .rules("add", { required: true }) and it still has problems. Here's my list of problems:

  1. With the .rules method of adding required, I get the error of settings being undefined. Plenty of SO answers say you need to re-validate the form first, which I tried, except that although it gets rid of the error, the field still doesn't become required.
  2. The way I have the code now, shown above, successfully makes the field required, but ONLY if it is set during document ready. If I change the select box after the load, it will never become required.
  3. The weirdest problem of all, no matter what I try, anything that gives any hint of success ruins the rest of the validation on the page. I have a bunch of other required fields. If my DateOfFirstCoverage field is successfully made to be required, and I fill it out but delete a different required field, the page happily submits without validation complaining about the other fields. This happens, for example, if part of my snippet looks like this:

    if ($("#StatusID").val() == 602) {
        $("form").validate();
        $("#DateOfFirstCoverage").rules("add", { required: true });
    }
    

So, what the heck is going on? What is the "correct" way to accomplish what I want without messing with the rest of my rules?

Upvotes: 1

Views: 2836

Answers (1)

Tesserex
Tesserex

Reputation: 17314

Figured this one out. The correct answer was available in one of the other posts - this one - but I had to figure out how to use it. The final script block is this:

<script type="text/javascript">
    function DateRequirement() {
        $("form").removeData("validator").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse("form");

        if ($("#StatusID").val() == 602) {
            $("#DateOfFirstCoverage").rules("add", { required: true, messages: { required: "A date is required for current members." } });
        }
        else {
            $("#DateOfFirstCoverage").rules("remove", "required");
            $("form").validate().element("#DateOfFirstCoverage");
            console.log("reset");
        }
    }

    $("#StatusID").change(DateRequirement);
    $(document).ready(DateRequirement);
</script>

Removing the validators at the top makes sure that unobtrusive validation doesn't bail out early because a validator is already hooked up. That solves my weird issue of why the other fields weren't validating. Then by asking unobtrusive to parse, there always will be a validator, so I can use the normal rules add method for the required rule.

Upvotes: 5

Related Questions