0

I am trying to validate dependent inputs field , but i am n't getting any idea..

Suppose i have 3 fields named first_name, middle_name and age . If all the fields are empty or blank then it is ok, but when first field is filled then other two must required & validate properly... so how could i achieve this using jquery. i am using jquery.js and jquery.validate.js

<script>
$(document).ready(function(){
     $("#frm").validate({
                rules:{
                    middle_name:{
            required: function(element) {
            return $('input[name="first_name"]').val() != '';
            }
                     }
                },
                messages:{
                      middle_name:{
                          required:"now it is mandatory.."
                },
});
});
</script>

1 Answer 1

2

Your code looks correct to me - just to make explicit what you need to do try markup like this

<form>
    <input type="text" name="first_name" id="first_name" class="required"/>
    <input type="text" name="middle_name" id="middle_name"/>
    <input type="text" name="last_name" id="last_name"/>
    <input type="submit" />
</form>

and you can use either a selector or a function as the value of a required parameter, I have used both below

$("form").validate({
    rules:{
        middle_name:{
            required:function(){
                 return $('input[name="first_name"]').val() != '';  
            }
        },
        last_name:{
            required:"#first_name:filled"
        }
    }
});

fiddle here

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

Comments

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.