pyy
pyy

Reputation: 953

Two different sets of jquery validation

At the moment, I have a form with parts that can be expanded or claposed depending on what data is being entered. If a part is closed, it is to be assumed that the user doesn't need to enter that data and as such it doesn't need to be validated.

This is the code I was trying (sorry for such bad practises, I'm still getting to grips with javascript):

    $( "#submit-form" ).submit(function( event ) {
    if ($("#CapTextBoxes").is(":visible")){
        if ($("#submit-form").validate({
            rules:{
                CapStartDate:{
                    required: true,
                }
            }
        })){
            alert("submitting");
        }else{
            event.preventDefault();
        }
    }else{
        if ($("#submit-form").validate({
            rules: {
                CapStartDate:{
                    required: false,
                }
            }
        })){
            alert("submitting");
        }else{
            event.preventDefault();
        }
    }
});

I was under the assumption that $("#submit-form").validate() returned true or false depending on if the form validated correctly, but regardless of if the form is correct or not, it will try to submit. Any help is much appreciated.

Upvotes: 0

Views: 32

Answers (1)

Indranil Mondal
Indranil Mondal

Reputation: 2857

Try the following:-

 if ($("#CapTextBoxes").is(":visible")){
    $("#submit-form").validate({
        rules:{
            CapStartDate:{
                required: true,
            }
        }
    });
    if(!$("#submit-form").valid()){
        event.preventDefault();
     }

}

Upvotes: 1

Related Questions