Reputation: 617
I've been looking but have not found a solution for my specific need. I have a total of 3 fields (first_name, last_name, and business_name). I want users to either enter both first and last name or just the business name.
I've several methods, here's my most recent attempt.
<input type="text" id="first_name" name="first_name">
<input type="text" id="first_last" name="first_last">
<input type="text" id="bus_name" name="bus_name">
rules : {
first_name1 : {
required: function(element){
return $("#bus_name").val().length = 0;
}
},
last_name1 : {
required : function(element){
return $("#bus_name").val().length = 0;
}
},
bus_name1: {
required : function(element){
return ($("#first_name").is(':empty') && $("#last_name").is(':empty') ? true : false);
}
}
I've also tried creating a custom method. Needless to say it didn't work.
$.validator.addMethod("busnameRequired", function(value, element) {
var firstname1 = $("#first_name").val().length,
lastname1 = $("#last_name").val().length;
if(firstname + lastname == 0) {
return true;
}else{
return false;
}
}, "Enter Business Name");
Thanks in advance!
Upvotes: 1
Views: 844
Reputation: 98728
Conditional Rules:
You have all kinds of little issues on the first attempt...
You declared a rule on first_name1
but this field is named first_name
. The plugin needs the correct name
attribute.
You declared a rule on last_name1
but this field is named first_last
. The plugin needs the correct name
attribute.
You declared a rule on bus_name1
but this field is named bus_name
. The plugin needs the correct name
attribute.
You're checking length on some rules but checking :empty
on the other. Use .is(':blank')
on all of them instead.
DEMO: http://jsfiddle.net/n8gvvb92/
Custom Method:
In your custom rule, your logic is backwards. You're presently returning true
when the name fields are empty. You will want to return false
in that case so that you trigger the validation error message.
You'll also want to use .is(':blank')
here too.
Something like this is closer to what you want, but will still need some work.
$.validator.addMethod("busnameRequired", function (value, element) {
return ($("#first_name").is(':blank') && $("#last_name").is(':blank')) ? false : true;
}, "Enter Business Name");
Upvotes: 1