Reputation: 3642
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
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 thereturn
statement, every time it returnstrue
. same occurs forcsv
."
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
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