user1019490
user1019490

Reputation: 11

jquery validation conditional statement?

I am using this jquery plugin: http://docs.jquery.com/Plugins/Validation

and I want to write a conditional statement.

If the user leaves a specific form field blank, then the field is not required. However, if they don't leave it blank, then it must start with a number

Upvotes: 1

Views: 3591

Answers (1)

No Results Found
No Results Found

Reputation: 102874

For the "must start with a number" part, I think you'll need a custom rule.

For the "required if another field is not empty" part, you can use a dependency expression to decide if it's required when the validator runs:

Put them together and you'll have something like this:

<form>
    <input name="first">
    <input name="second">
</form>
$.validator.addMethod("startsWithNum", function(input, element) {
    // First char must be digit if not empty
    return ! input || input.match(/^[0-9]/);
}, "This field must start with a number");

$('form').validate({
    rules: {
        first: {required : true},
        second: {
            "startsWithNum" : true,
            required: function() {
                // required if <input name="first"> is not empty
                return $('[name="first"]').val() !== '';
            }
        }
    }
});

Demo: http://jsfiddle.net/qCELA/2/


There is only a single input in the form I need to make. If the user left it blank, then no rules apply. Otherwise, that single input field must start with a number.

If you only have one input field, the custom rule is all you need:

$('form').validate({
    rules: {
        second: {"startsWithNum" : true}
    }
});

Demo: http://jsfiddle.net/qCELA/3/

Upvotes: 8

Related Questions