Vincent McNabb
Vincent McNabb

Reputation: 34719

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 blank.

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.

Upvotes: 0

Views: 3502

Answers (3)

maček
maček

Reputation: 77786

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

Upvotes: 6

Khawer Zeshan
Khawer Zeshan

Reputation: 9646

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');
    }

Upvotes: 0

karim79
karim79

Reputation: 342665

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:

Upvotes: 2

Related Questions