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

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’m trying to get validation working on an entry that must be exactly 10 characters. The following will error, but will not succeed:

lp.jQuery(function($) {
         
           // Config
         var ruleID = 'promoCode';
         var field = 'redemption_code';
         var message = 'The code appears to be invalid';
         
         var rules = module.lp.form.data.validationRules[field];

          $.validator.addMethod(ruleID, function(value, field) { 
          
          var valid = ( /^[A-za-z0-9]{10}$/i.test(value) );
        }, message); 
  
  rules[ruleID] = true; 

});

Any help would be appreciated.

Thanks,
Brian

Figured it out.

lp.jQuery(function($) {
         
           // Config
         var ruleID = 'promoCode';
         var field = 'redemption_code';
         var message = 'The code appears to be invalid';
         
         var rules = module.lp.form.data.validationRules[field];

          $.validator.addMethod(ruleID, function(value, field) { 
          
         var exp = new RegExp('^[A-za-z0-9]{10,11}$', 'i');
		 return value.match(exp) ? true : false;
        }, message); 
  
  rules[ruleID] = true; 

});

Hello there,

I’m tryng to have a field that only should acept 3 letters or 4 letters.
If less than 3 letters should give error and if more than 4 letters should give error.

What is missing?

var valid = ( /[a-zA-Z]{3}|[a-zA-Z]{4}/.test(value) );

Thank you

Any help?

Thank you

Hello,

I’m looking for a digit only field in unbounce and I’m having some trouble.

i used:

I updated the field ID to reflect the one I wanted to be digits only but it didnt work.

Can somebody please help advise.

Userlevel 7
Badge +3

Hi @getreel,

Can we see the page you are working on so we can try to troubleshoot this for you?

Best,
Hristian

Hi guys.
Is there a way to make this code works on my page?
It should validate a brazilian mobile phone number and use a mask to help the user fill the form correctly.
Here’s the script that I have to put on unbounce:

<script src="http://digitalbush.com/wp-content/uploads/2014/10/jquery.maskedinput.js"></script>

<script>
ijQuery(document).ready(function () {
    var fieldLabel = 'ddd__telefone';
    ijQuery.validator.addMethod('validatePhone', function (value, element) {
        var phoneNoRegex = /^\+?\d{2}?\s*\(\d{2}\)?\s*\d{8,9}/;
        if (value.match(phoneNoRegex)) {
            return true;
        } else {
            return false;
        }
    });
    $('form [name="' + base64_encode(fieldLabel) + '"]').mask("+55 (99) 99999999?9");
    ijQuery('form [name="' + base64_encode(fieldLabel) + '"]').addClass('validatePhone');
    ijQuery.extend(ijQuery.validator.messages, {
        validatePhone: ': Inserir um telefone válido.'
    });
 });
</script>

My Field ID is the “ddd__telefone”.

thanks

can anyone help?

Userlevel 5

I would suggest starting with one of the examples given by the Unbounce team at the top of this post and then add your regex.

There is some syntax you are missing and I think it would just be easiest to mimic one of the examples and go from there.

Thanks for helping, Kyle! I’m not really a coder, so that’s why I’m not sure where to insert this code into the base one from the example. If anyone could help, this would be great.

Userlevel 5

Oh okay,

Well keeping the code simple there is no if, else, that involves a mask. You can add this script to your page in the “Before Body End Tag” and it will validate based on the regex you included.

Hope that helps

Thanks a lot, Kyle! This would definetly helps!

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.

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/

Hey @claudias! For your specific implementation it may be the case that you’re calling the .validator method before (document).ready. Try including your script in a $(document).ready block.

It would look something like this:
$(document).ready(function () { /* your script*/ });

If that doesn’t work, we can keep digging!

that is instead of my first line right?
it would look like:

    $(document).ready(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;
    	 });

right?

not working 😦

Userlevel 2

@claudias @mccamon Sorry, this one’s on us – we made a behind-the-scenes change a few days ago that is causing the errors you’re seeing. We’re testing a fix at the moment and are aiming to have that in place tomorrow. Sorry for any inconvenience this has caused. I’ll update this thread when the fix has been released.

@Mark_Wainwright Do you have any update on this? Seems every-time I get into work this problem is getting worse not better.
I currently have at least three different contingencies to deal with Unbounce not having loaded validation in early enough…

Just to further my last reply… I’ve been working at this for several hours today… then I noticed that a script I had deleted 4-5 hours before was still appearing in the final published version… (multiple saves, republishes, set to 1% republish set to 0% republish)…
I was then trying to explain to my superior exactly what was going on… then Refreshed not republished the page. (Keep in mind I’ve republished and refresh many times.) The script that I deleted earlier vanished, and the script I’ve been trying to debug suddenly started to work…
Is it worth my doing any work at the moment until I can be sure what I see in the landing page reflects what is in the editor?

Userlevel 5

@TimothyDO @claudias @mccamon

Correct me if I’m wrong @Mark_Wainwright I believe the Unbounce team corrected the “behind-the-scenes” change this past Friday (7th of September) and scripts should now be working as they should.

Userlevel 2

@claudias @mccamon @TimothyDO

You’re correct @Kyle.C, we pushed out a fix for this on Friday afternoon (apologies for not updating this thread sooner). You’ll just need to republish any affected pages, popups, or sticky bars.

Sorry again for the inconvenience – and please reach out to our support team if you experience any further issues.

I’m still getting the same error 😦

Uncaught TypeError: Cannot read property ‘addMethod’ of undefined

Userlevel 5

Hey @claudias

Where is the field named “valor_monetario” I don’t see that in your form or as any of the form Id’s.

The script is looking for that field to validate the entry, but it doesn’t exist and therefore is undefined.

Reply