benoit
benoit

Reputation: 157

jQuery validation plugin : prevent submit if there's an error in a field that's not required

In my form, I have multiples text inputs for email addresses.

Only the first one is required.

My problem is that the form is submitted when the user has typed an invalid email address in a field that's not required.

I need to prevent the form submit if there's an error in a field that's not required.

How can I do that ? Should I add a custom rule ?

Here's what I have in my form.

<fieldset>
    <label for="To"><span>To</span> <input id="To" name="To" type="email" autocomplete="off" maxlength="30" class="required"></label>
    <label for="Cc1"><span>Cc</span> <input id="Cc1" name="CC[]" type="email" autocomplete="off" maxlength="30" ></label>
    <label for="Cc2"><span>Cc</span> <input id="Cc2" name="CC[]" type="email" autocomplete="off" maxlength="30" ></label>
</fieldset>

And the initialization for the jQuery plugin

$.metadata.setType("attr", "validate");

$().ready(function() {
    // validate signup form on keyup and submit
    $("#myform").validate();
});

Upvotes: 1

Views: 869

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

Add the email validation rule to your email field. It won't be required but will be checked for a valid email address if there is a value.

<input id="Cc1" name="CC[]" type="email" class="email" autocomplete="off" maxlength="30" >

Check this working example on jsfiddle.

Upvotes: 1

Related Questions