Adding custom validation to form fields


Userlevel 2

If you want to add more specific form validation rules, you can do that using custom JavaScript!


How to Install in Unbounce

Click Here for Instructions

🚨
This is not an official Unbounce feature. This functionality is based entirely on third party code, and has only been tested in limited applications. Since this isn’t a supported Unbounce feature, our support team will be unable to assist if things go awry. So if you are not comfortable with HTML, Javascript and CSS, please consider consulting an experienced developer.


Part 1: Define a validation rule

  1. Copy the following script and paste it into the Javascripts section of the builder:

    <script>
      window.ub.form.customValidators.myCustomRule = {
        isValid: function(value) {
          return value === 'I accept';
        },
    
        message: 'Your entry is invalid',
      };
    </script>
    
  2. Replace myCustomRule with a unique ID (name) for the rule. You’ll need this later.

  3. Replace isValid with a function that takes the value as an argument and returns true if the value passes validation, or false if not. (The above example requires the user to enter ‘I accept’ exactly.)

  4. Replace message with the error message that you would like to show when the user’s input does not match (optional)

Part 2: Apply the rule to form field(s)

  1. Copy the following script and paste it into the Javascripts section of the builder:

    <script>
      window.ub.form.validationRules.my_form_field.myCustomRule = true;
    </script>
    
  2. Replace my_form_field with the ID of the form field you want to apply the rule to

  3. Replace myCustomRule with the rule ID you set when defining the rule above

This part of the script can be repeated if you would like to apply the same validation rule to multiple form fields.

Examples

Here are some examples of validations that this can be used to create:

Canadian postal codes

<script>
  window.ub.form.customValidators.canadianPostalCode = {
    isValid: function(value) {
      return /^([a-zA-Z]\d[a-zA-z]\s?\d[a-zA-Z]\d)$/.test(value);
    },

    message: 'Please enter a valid Canadian postal code',
  };
</script>

US ZIP codes

<script>
  window.ub.form.customValidators.usZipCode = {
    isValid: function(value) {
      return /^\d{5}([\-]?\d{4})?$/.test(value);
    },

    message: 'Please enter a valid US ZIP code',
  };
</script>

Non-webmail email addresses

<script>
  window.ub.form.customValidators.nonWebmailEmail = {
    isValid: function(value) {
      return /\@(?!(me|mac|icloud|gmail|googlemail|hotmail|live|msn|outlook|yahoo|ymail|aol)\.)/.test(value.toLowerCase());
    },

    message: 'Please enter your work email address',
  };
</script>

Can’t see the instructions? Log-in or Join the Community to get access immediately. 🚀


Want to take your Unbounce landing pages + Convertables™ to the next level?
:spinbounce: Check out the Ultimate List of Unbounce Tips, Scripts & Hacks


112 replies

Ok, seriously, why are we still custom coding form validation for really simple requests, like simply validating something is a number. This is really frustrating.

Secondly, the instructions at the top of this don’t seem to work. Or are confusing enough that they are difficult to implement. This seems pretty straight forward:

<script>
window.module.lp.form.data.validationRules['field_name'].digits = true;
</script>

But no. It isn’t. The instructions don’t tell you where to include it: head, after body, before body, etc. Although that doesn’t matter because I’ve tried them all and it doesn’t work.

Of course, I’ve seen a reference in this thread to JQuery no longer being supported or plans to remove it, so I don’t know if this thread is still valid, except that I chatted with customer support and this is what they pointed me to.

I’m beyond frustrated with this.

Userlevel 3

Here’s a couple others

Digits only
https://gist.github.com/johnnyopao/51…

Currency up to two decimals (ex: 45.50)
https://gist.github.com/johnnyopao/86…

Confirm email
https://gist.github.com/johnnyopao/c9…

Hello,

I was wondering if Unbounce’s decision to remove jQuery from the landing pages would affect the validation scripts shared in this thread.

If Unbounce is removing jQuery from the lp object then what would be their alternative rather than using jQuery’s .validator plugin which is what is currently recommended?

Any further direction would be appreciated.

Thank you

  • Jon S.
Userlevel 1

Hi guys,

Unfortunately, web traffic isn’t always great. Especially when you’re receiving a lot of spam leads. With the following scripts you can at least block non work email addresses.

//Placement: Before Body End Tag

<script>
  window.ub.form.customValidators.nonWebmailEmail = {
  isValid: function(value) {
  return /(@(?!me|mac|icloud|gmail|googlemail|hotmail|live|msn|outlook|yahoo|ymail|aol).)/.test(
  value.toLowerCase()) && /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
  value.toLowerCase());
},

  message: "Please enter your work email address"
};
</script>

and…

//Placement: Before Body End Tag

<script>
  window.ub.form.validationRules.email.nonWebmailEmail = true;
</script>

@k.colvin 

In your second script, make sure that you’re targeting the correct field. 

From what I see in your script:

<script>
  window.ub.form.validationRules.lp-pom-form-16.nonWebmailEmail = true;
</script>
 

 

it looks like you may be targeting a larger section than just the email field. Click into your form editor and look for what your form field ID is. This is what it is by default, but you may have edited yours:

 

 

Using the default example, the second code should look like this:

 

<script>
  window.ub.form.validationRules.email.nonWebmailEmail = true;
</script>

 

Try that out and let me know if you have any questions!

Hi there,

I need some help to add a “Country Code” field to our landing pages on Unbounce, just before the Phone Number field. We are getting a lot of international inquiries and need to know their country code’s to be able to call them back.

Any help would be greatly appreciated.

Userlevel 3

Hey Nayon

It looks to be working for me

I assume you got it figured out, but let me know if you’re still having issues with it

Userlevel 6

Hi @bmiksich Unbounce actually has a built in honeypot field already included as a way to combat spam, so no need to worry about setting one up on your own. We don’t make it visible in the builder since it’s purpose is to filter out leads that fill it out. One of those behind the scenes features that isn’t really visible within the app.

I tried using this code and I get an error in the console and the validation is not working

Uncaught TypeError: Cannot read property ‘addMethod’ of undefined
at HTMLDocument. ((index):2992)
at Function.ready (lp-jquery.bundle-fc9ca0c.z.js:1)
at HTMLDocument.i (lp-jquery.bundle-fc9ca0c.z.js:1)

I am trying to validate a number range in a text field:

lp.jQuery(function($) {
	    var ruleID = 'range';
	    var field = 'valor_monetario';
	    var message = 'El valor debe ser entre $500,000 MXN y $20,000,000 MXN.';
	    var rules = module.lp.form.data.validationRules[field];
	    $.validator.addMethod(ruleID, function(value, field) {
	      var valid = ( value >= 500000 && value <=20000000 )
	      return valid || (!rules.required && !value);
	    }, message);
	    rules[ruleID] = true;
	 });

any idea? thanks!

This is my landing: https://negocio.iontucasa.com.mx/

Hi, I’m trying to add custom field validation to my form but it’s a multi-step form built with this method (Multi-Field, Multi-Step Form 🔥) and I suspect it doesn’t work because of that… Any input?

Userlevel 6
Badge +4

Hi @Mark_Wainwright, is it possible to get the email validation script to also validate that the entry includes a “domain extension”? With the current script you can submit emails without .com or similar - in other words invalid emails.

Userlevel 5
Badge +4

yes, that would be a good idea.
i still regularly get emails without domain extension

That was it - thanks!!!

Userlevel 4
Badge +1

For anyone who comes across this thread, we recently added a similar option while you’re editing your forms within the builder directly. Check it out here!

In the example above, how would I change “I Accept” to check another field for matching information (i.e. email confirm field). I already added another field var, but can’t seem to get the snytax right to replace 'I Accept". Thanks.

Userlevel 3

Hey Hayley - Sorry i’m a bit confused as to what you’re trying to do.

Did you want to check if another field to see if it was filled out? Or you want this field field to match the exact value as another field? Or something else completely?

We want the two field to match exactly. We have an “email” field and then a “confirm email” field. So the custom validation needs to “match the exact value as another field”. Does that make sense?

email field 1 == email field 2

Userlevel 3

Thanks for clarifying Hayley

As this is something I can see asked for more frequently, I whipped up a validation myself

https://gist.github.com/johnnyopao/c9965db11cded79aede6

Be sure to update the IDs with your own email fields

Badge

I am running into issue with the business email validation code and not sure if anyone can help me. Currently I have 3 javascripts set up for this page: https://m.jobtarget.com/safeguard-your-business-from-compliance-violations-b/

I also created an additional 2 more javascripts for the business email validation. The first has this code:

<script>
  window.ub.form.customValidators.nonWebmailEmail = {
    isValid: function(value) {
      return /\@(?!(me|mac|icloud|gmail|googlemail|hotmail|live|msn|outlook|yahoo|ymail|aol)\.)/.test(value.toLowerCase());
    },

    message: 'Please enter your work email address',
  };
</script>

The second file has the following:

<script>
  window.ub.form.validationRules.lp-pom-form-16.nonWebmailEmail = true;
</script>

Lp-pom-form-16 is the ID for our form on this page. I was wondering what I was doing wrong as I am able to put my personal gmail address in and it does not block it?

Thanks, works!!

Johnny, you’re the man!

Hi Johnny,

I tried to use your script to validate the field ‘cod_fisc’ in my form, which must be an alphanumeric string as follows:
[6 letters] [2 numbers] [1 letter] [2 numbers] [1 letter] [3 numbers] [1 letter]

below my script:

however, it does not function. Where am I wrong?

thanks for your help

cancelled

Userlevel 7
Badge +3

Hi Joe, 

I just checked your RegEx with this tool and it seems to be working as intended. 

![](https://d2r1vs3d9006ap.cloudfront.net/s3_images/1328514/RackMultipart20151214-14187-obpi08-Online_regex_tester_and_debugger JavaScript Python PHP and_PCRE_inline.png?1450078755 “Image: https://d2r1vs3d9006ap.cloudfront.net/s3_images/1328514/RackMultipart20151214-14187-obpi08-Online_regex_tester_and_debugger__JavaScript__Python__PHP__and_PCRE_inline.png?1450078755”)

Have you tried closing it with parentheses on both ends (). 

![](https://d2r1vs3d9006ap.cloudfront.net/s3_images/1328515/RackMultipart20151214-26309-jc3rnz-This_validates_a_field_for_currency_for_dollar_and_cents Ex 42_50___GitHub_inline.png?1450078768 “Image: https://d2r1vs3d9006ap.cloudfront.net/s3_images/1328515/RackMultipart20151214-26309-jc3rnz-This_validates_a_field_for_currency_for_dollar_and_cents__Ex__42_50___GitHub_inline.png?1450078768”)

That’s the only thing I can spot out of place with the original script example. 

Best,
Hristian

Hi Hristian,

I tried closing it with parentheses on both ends as you suggest, but still does not work

any other suggestions?

thanks for your time

J

Reply