Huy Guys,
I am trying to use jQuery validation plugin and specify that one field is required only when 3 other fields are blank (not filled).
the thing is that the rule is working but it still remain requiring the field even when I type value on it.
Thanks.
This is my code:
$("#ProspectDtlFrm").validate({
rules: {
prsptEmail: {
required: function(element) { return ( $("#prsptHomePhone").val() == '' && $("#prsptBusinessPhone").val() == '' && $("#prsptMobilePhone").val() =='') }
}
},
messages: {
prsptEmail: "Please enter your first name"
}
});
You could use depends
:
$('#ProspectDtlFrm').validate({
rules: {
prsptEmail: {
required: {
depends: function(element) {
return ($('#prsptHomePhone').val() == '' &&
$('#prsptBusinessPhone').val() == '' &&
$('#prsptMobilePhone').val() == '');
}
}
}
},
messages: {
prsptEmail: 'Please enter your first name'
}
});
The depends
clause is still supported. This is from 1.11.0pre version:
normalizeRules: function(rules, element) {
// handle dependency check
$.each(rules, function(prop, val) {
// ignore rule when param is explicitly false, eg. required:false
if (val === false) {
delete rules[prop];
return;
}
if (val.param || val.depends) {
var keepRule = true;
switch (typeof val.depends) {
case "string":
keepRule = !!$(val.depends, element.form).length;
break;
case "function":
keepRule = val.depends.call(element, element);
break;
}
if (keepRule) {
rules[prop] = val.param !== undefined ? val.param : true;
} else {
delete rules[prop];
}
}
});
As you can see, yo can choose between "string" and "function". So you can use:
rules: {
input_name_here: {
required: {
depends: function(element) {
return $("#thickBoxId:checked").length;
//or whatever you need to check
}
}
}
}
Or
rules:{
input_name_here:{
required: '#tickBoxId:checked'
}
}
If you only need to test for the existence of something checked.
'depends' seems like it's not supported any more, and, their docs are not up to date.
So in the scenario where if a 'yes' tick box is checked, validate another field:
rules:{
'name value of area you want to validate':{
required: '#tickBoxId:checked'
}
}
the way is depends
it's works.
rules: {
prsptEmail: {
required: {
depends: function(element){
if ($('#id-user').val() == '') {
return true;
} else {
return false;
}
}
}
},
},
messages: {
prsptEmail : {
required : "please signIn!",
}
},
来源:https://stackoverflow.com/questions/3975778/jquery-validate-depend-field