0

I have 3 text fields.

The first field is the only mandatory field, but if the second field is not empty the first and third text field should not be empty.

How to do this validation in jquery?

0

2 Answers 2

1

Simple:

var set = $('input[type="text"]');
if(set.eq(0).val().length == 0 || (set.eq(1).val().length > 0 && set.eq(2).val().length == 0)) {
   //throw error
} 
Sign up to request clarification or add additional context in comments.

1 Comment

should probably have $.trim in there too.
0

I think this is a simple logical algorithm

if ($('#field2').val() != '' && ( $('#field3').val() == '' || $('#field3').val() == '')) {
    return false;
}

Otherwise, You can find some plugins to validate form there : http://docs.jquery.com/Plugins/Validation

1 Comment

FWIW, comparing strings is more expensive than checking the length of them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.