Shahzeb Khan
Shahzeb Khan

Reputation: 3642

jquery validation plugin for form

I am trying to validate a form having two fields string email and file type file (one of the two is mandatory). I am validating the form with following code,

$("#addOrganizationMembersForm").validate({
        rules : {
            csv : {
                required : "#emails:empty",
                extension: "xls|csv"
            },
            emails : {
                required : "#csv:empty"
            }
        },
        messages : {
            csv : {
                required : 'Upload a csv or xls file',
                extension : 'Only csv files are allowed',
            },
            emails : {
                required : 'Enter one or more comma seperated emails',
            }
        }
    });

This code is validating both fields (But for me if one of the two fields has value i.e email or csv file, then form is valid)

Kindly help me, what is wrong with this code

Upvotes: 2

Views: 296

Answers (2)

Sparky
Sparky

Reputation: 98718

Quote OP's Comment:

"Thanks rohan for replying. i have already tried this, and the thing is if i add console.debug($("#emails").is(':empty')) statement before the return statement, every time it returns true. same occurs for csv."

When you have two fields where the required rule on each is dependent upon the other being empty, there are timing issues... you satisfy one field but then you might have to re-trigger validation on the other to clear the error.

However, if you include the additional-methods.js file, you can just use the require_from_group rule which already does exactly what you want. (Must use plugin version 1.11.1 or later)

$("#addOrganizationMembersForm").validate({
    rules: {
        csv: {
            require_from_group: [1, '.mygroup'],
            extension: "xls|csv"
        },
        emails: {
            require_from_group: [1, '.mygroup']
        }
    },
    messages: {
        csv: {
            require_from_group: 'Upload a csv or xls file',
            extension: 'Only csv files are allowed',
        },
        emails: {
            require_from_group: 'Enter one or more comma seperated emails',
        }
    }
});

Working DEMO: http://jsfiddle.net/h9WpL/

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$("#addOrganizationMembersForm").validate({
     rules : {
            csv : {
                required : function(){
                              return $("#emails").is(':empty')
                           },
                extension: "xls|csv"
            },
            emails : {
                required : function(){
                              return $("#csv").is(':empty')
                           },
            }
        },

Upvotes: 1

Related Questions