Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery Validation Plugin validate all fields?

I had the jQuery Validation plugin running on a few forms but was not entirely happy with it so I moved to a different solution. After a while I found I needed to return to the plugin but I can not get it working properly. For some reason, it wants to validate ALL fields in the form, not just those with rules.

Here is the form:

<form id="test-form">
    <div class="form-group">
        <label for="firstName">First Name</label>
        <input type="text" name="firstName" id="firstName">
    </div>
    <div class="form-group">
        <label for="lastName">Last Name</label>
        <input type="text" name="lastName" id="lastName">
    </div>
    <input type="submit">
</form>

Here is the javascript:

    $.validator.setDefaults({
        errorClass: 'help-block',
        errorElement : 'span',
        ignoreTitle : true,
        highlight : function (element, errorClass, validClass) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight : function (element, errorClass, validClass) {
            $(element).closest('.form-group').removeClass('has-error');
        }
    });

    $('#test-form').validate({
        rules: {
            firstName: {
                required: true
            }
        },
        messages: {
            firstName: {
                required: 'First name is required'
            }
        }
    });

When I run it (with both form fields blank) I get the expected error message for firstName, but I also get an error for lastName. The message simply says 'message'.

I really can't see what I am doing differently this time around, but obviously it must be something!

like image 678
DatsunBing Avatar asked Jan 01 '26 05:01

DatsunBing


1 Answers

You need to tell the Validation plugin to ignore the lastName field

$('#test-form').validate({
    ignore: '#lastName',
    rules: {
        firstName: {
            required: true
        }
    },
    messages: {
        firstName: {
            required: 'First name is required'
        }
    }
});
like image 60
J. Titus Avatar answered Jan 03 '26 07:01

J. Titus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!