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:
- With the .rulesmethod 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.
- 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.
- 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 - DateOfFirstCoveragefield 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?
 
    