1

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

1
  • What have you got so far? It'd be easier to tell you what you are missing if you show your JS (and the related HTML). Commented Oct 29, 2011 at 7:07

1 Answer 1

8

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/

Sign up to request clarification or add additional context in comments.

3 Comments

in your answer there were two input fields. there is only a single input in the form I need to make. I need the rule for that single input to change depending on whether or not the visitor left that single input field blank or not. If the user left it blank, then no rules apply. Otherwise, that single input field must start with a number.
OK, I thought you meant two separate fields. In that case, just remove every rule except startsWithNum, see edit.
Looking at the first example now, it doesn't make sense - both fields are effectively required. It would make sense with another setup though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.