How to validate in jQuery only if all fields are blank
Using jQuery validation, if I have many fields on a page, and only require ONE of them to be filled, how do I raise an error only if they are all bla开发者_JAVA技巧nk.
That is, the user can fill one or more fields, but if all of them are blank, there will be an error. I want to know if there is a way of doing this with jQuery validation.
Something along these lines should work.
var valid=0;
$("#myform input[type=text]").each(function(){
if($(this).val() != "") valid+=1;
});
if(valid){
console.log(valid + " inputs have been filled");
}
else {
console.log("error: you must fill in at least one field");
}
See a working example here on jsFiddle
var filled = $("#theForm :input").filter(function() {
return $.trim(this.value).length;
});
if(filled.length) {
// at least one has been filled
} else {
// error, all are blank
}
You can test it here.
Reference:
- http://api.jquery.com/input-selector/
- http://api.jquery.com/filter/
try this ,
var name = $('#name').val();
var city = $('#city').val();
if(name == '' && city == '') // this will only fire when both name and city are empty if one of them is not empty than this if condition will not fire
{
alert('all fields are required');
}
精彩评论