Modify form validation to block a particular value from a dropdown


#1

In a form we created, we needed to be able to block people who completed the form with a particular value for a dropdown from having a successful form submission.

This could be useful in cases where you wanted to prevent people from just selecting one of the default options so that they could submit the form. In our case, we had unqualified international leads submitting a form intended for only three countries.

Here’s how we did it. Mark Wainwright of Unbounce gave me the head start with code he shared on another thread (about blocking email addresses from unverified providers). The main thing I did was just to switch to using a simple indexOf match instead of regex.

lp.jQuery(function($) {





 var ruleID = 'notForeignCountries';



var field = 'country';



var message = 'Only people living in the US, Canada, and the United Kingdom may inquire through this form.';





 var rules = module.lp.form.data.validationRules[field];





 $.validator.addMethod(ruleID, function(value, field) {



  var valid = false;



  if(value.indexOf("Other") == -1) {





 valid = true;



  }



  return valid || (!rules.required && !value);



}, message);





 rules[ruleID] = true;



  });

The main things you would change are ruleID, field (which is the machine name of the field), message (what the user will see on failure), and the line that indicates what value makes it fail - in our case “Other.” You could add or conditions to the JS if you wanted multiple failing values.


#2

Hey Andrew - Thanks so much for sharing this!

With the default behaviour for forms, we’ve designed them to take the most common use case into account (which is not stopping anyone other than bots from converting), but there are definitely tons of less common use cases where unique validation like this helps you hone in on a certain segment of potential leads, which is why we give you the ability to get modify the behaviour with javascript.

It’s awesome to see you take what Mark wrote for free email domains and transform that.