SoftwareSavant
SoftwareSavant

Reputation: 9757

Jquery Validation required vs not required

I have a jquery validation plugin. I don't want my form to submit if there are certain things that are not right about it. I don't want it to submit if it doesn't have a certain date field or another certain varChar(25) field. I also want to make sure that it doesn't submit if a certain field has over 4000 characters in it. If that same field has no characters then it is ok to submit the form. For that to work with jquery validation, would I need to make that a requried validation?

$("#temp1").validate({
        rules: {
            HospitalFinNumber: {
                required: true,
                minlength: 6
            },
            DateOfBirth: {
                required: true
            },
            AdmitDate: {
                required: true
            },
            Comment: {
                maxlength: 4000
            }
        },
        messages: {
            HospitalFinNumber: 'Please Enter a Hospital Fin number',
            DateOfBirth: 'Please enter a valid Date Of Birth',
            AdmitDate: 'Please select an Admit Date'
        }

Notice how I have the first 3 fields as required and the last one is not required. I have tried to submit the form and it does indeed post back to the server if there is more than 4000 characters in that field. That would be a problem. I need to make this field conditionally required somehow. Also, if required is set to true, you should not be able to submit the form with those fields filled out right?

Upvotes: 2

Views: 3059

Answers (1)

Simeon
Simeon

Reputation: 5579

You have two options here; either write custom validation classes, or use required's dependency expression instead of just true. I think the latter is prettier.

See the docs on this. Here's how to make your Comment field optionally required, depending on length:

required: function(element) {
    return $(element).val().length > 4000;
}

Upvotes: 3

Related Questions