EmmyS EmmyS - 6 months ago 32
jQuery Question

Most efficient js/jquery way to prevent submission of empty fields (including spaces)

I have an advanced search form in a custom CMS. I need to check to make sure that the user doesn't try to submit the form without at least one field populated. No problem; this is a very stripped-down version:

var noText = false;

if(!$('#advancedId').val() && !$('#advancedTitle').val() &&
$('#advancedCoupon').val() && !$('#advancedDesc').val() ) {
noText = true;
}


if(noText) {
alert("You haven't provided any search terms. Please fill in/select at least one field.");
noText = false;
return false;
}


But we have that one QA guy who just has to really do his job, and deliberately tries searches that there's no way our client would ever do. He submitted a bug indicating that if he entered a space in every field, it passes and tries to submit.

So I tried trimming the values like this:

if(!$('#advancedId').val().trim() && !$('#advancedTitle').val().trim() &&
$('#advancedCoupon').val().trim() && !$('#advancedDesc').val().trim() ) {
noText = true;
}


This of course works if I actually enter a space in all of the fields, but throws a "Cannot read property 'trim' of null" error if I try to submit it with a space in one field, and nothing in the others.

Yes, I could do something like this:

if($('#advancedId').val()) {
$('#advancedId').val($('#advancedId').val().trim());
}


Yes, I could make it somewhat shorter with a terniary, but I'd still have to do that for over a dozen fields. Is there a better way to do this?

Answer Source

I would probably select them all and then do a filter. Though to make it less tightly coupled, I'd probably put a class on them and select with that instead of all the ids.

//select all the fields concerned and filter on them for non-blank values
var nonBlankFields = $('#advancedId, #advancedTitle, #advancedCoupon, #advancedDesc').filter(function(){
  //default to an empty string if for some reason the value doesn't exist
  return ( this.value || '' ).trim().length > 0
});

if (!nonBlankFields.length) {
    alert("You haven't provided any search terms. Please fill in/select at least one field.");
    return false;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download