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

The US Zip code Validation is not working, can someone help me?

I’m in the same boat, if anyone has a way to get US Zip Code validation working I would really appreciate the help!!

Badge

I have tried the US Zip Code validation script in the original post. It’s not accepting any answer in that field even though I’ve entered a valid zip code.

(before body end tag)

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

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

and also (before body end tag)

 <script>
   window.ub.form.validationRules.zip.usZipCode = true;
 </script>

Any suggestions on getting this to work? Thanks!

Did you add these to the Script Manager or to each individual landing page’s custom javascript? Thanks!

Hi, i’m facing this issue when i run my code below:

<script>
  window.ub.form.customValidators.validacao_telefone = {
    isValid: function(value) {
      /(\(\d{2}\)\s)(\d{4,5}\-\d{4})$/.test(value);
    },

    message: 'Informe um telefone válido',
  };
</script>

“TypeError: window.ub.form is undefined”

My page: http://unbouncepages.com/amildental/

Userlevel 5
Badge +4

Hey @Eline_M !

Did you find a solution to your problem ?

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

I’ve already put in feature requests on solving this… problem is that it’s a valid email without the domain… e.g. test@localhost or employee@companyintranet . so by using html5 email validation these are technically correct although completely useless for a internet only system.

Our solution goes something like:
document.getElementById('email_field_id').setAttribute("pattern", "[a-zA-Z0-9.-_]{1,}@[a-zA-Z0-9.-]{1,}[.]{1}[a-zA-Z0-9]{2,}");

Drop the above into a script and change email_field_id to the id of the email field on your form.

This uses html5 regex pattern matching to use as validation for valid emails (with domain) 😉

HEllo, Can you send me page file with validate postall code. It will be helpful.
Thank you sir.

Hi there Enayet!

Tas from Unbounce Support here - I’m happy to take a look for you 🙂 . Do you mind sharing a link to your landing page and I can see what you have so far?

Here is an example test page of mine with the Postal Code Validation: http://unbouncepages.com/testing-tas-form-validation-email/

To re-cap, you will need to set up two scripts with the placement for both set to “Before End Body Tag”.

If you’re still having issues, just thread here, or reach out to support via support@unbounce.com.

Hi Guys,

I put that script buth dont fix.

<script>
lp.jQuery(function($) {
         
           // Config
         var ruleID = 'OnlyNumber';
         var field = 'teste1';
         var message = 'Only Number';
         
         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; 

});
</script>

why?

hello, for some reason, the above “confirm email” scripts to validate two email fields was not working for me. This one to be exact: https://gist.github.com/johnnyopao/c9965db11cded79aede6

In the console (in the Chrome “Inspect” section), I kept getting an error saying “lp is not defined”. I wrote another script based on the original which does the same thing, but does not include lp.jQuerry. this script checks two emails, but can be applied to any two fields that you want to be the same

<script>
window.ub.form.customValidators.emailCheck = {
    isValid: function (value) {

        var firstEmailField = 'email'
        var secondEmailField = 'email_'


        var emailValue = $('#' + firstEmailField ).val();
        var emailValue2 = $('#' + secondEmailField ).val();

        if (emailValue === emailValue2) {
            return value;
        }
    },
    message: 'email addresses do not match',
};</script>

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

few things to note:
-the “emailCheck” in this line “window.ub.form.customValidators.emailCheck” should be changed to your unique ID for whatever function you’re doing (and everywhere else it is referenced).
-the two identifiers in these lines "var firstEmailField = ‘email’ var secondEmailField = ‘email_’ " should be changed to the two field names and identifiers that you want to compare.
-change the message to whatever you want
change the “email” in “window.ub.form.validationRules.email.emailCheck = true;” to whatever field you want the message to pop up on.

copy and paste this into your scripts section and it should work.

I have finally worked on a solution to validate Indian phone number and it’s live on the landing page.

The complete step by step process is here

There are 3 elements for this:

1) Regex for Indian phone number validation

^[6-9]{1}[0-9]{9}$/g

2) Unbounce Javascript 1

 <script> window.ub.form.validationRules.mobile.indianPhoneNumber = true; </script>

3) Unbounce Javascript 2

<script>
  window.ub.form.customValidators.indianPhoneNumber = {
    isValid: function(value) {
      return /^[6-9]{1}[0-9]{9}$/g.test(value);
    },

    message: 'Please enter a 10 digit phone number',
  };
</script>

Maybe this has already been answered - but if the field is left blank, the validation doesn’t work.

For example, if I set the required value to be “123”, if the user simply leaves the form blank and hits submit the validation doesn’t work and the form is submitted.

Any suggestions?

Userlevel 7
Badge +3

Hi @Evan-Dario,

Have you tried making the field required?

You can’t submit an empty field that’s also required.

Best,
Hristian

That was it - thanks!!!

Hi,
I have a email field and if I enter invalid email(test@test.com) into that, i am populating a value(invalid) into a hidden field(another field). If hidden field value has “invalid”, i need to show a error message and need to prevent form submission.

Below is my code:

window.ub.form.customValidators.Email_Verification_Status__c = {
isValid: function (value) {
var firstEmailField = ‘Email_Verification_Status__c’
var emailValue = $(’#’ + firstEmailField ).val();
if (emailValue == “valid”) {
return value;
}
},
message: ‘Not a valid email address’,
};

Any help would be great.

Yes, I can help you…

@Enayethazari1,

Please check my code is this correct? Or Just update the code and place that here. So that I can use it for my page.

@Enayethazari1

Could you please help on this? This is a critical item for me.

Hi all,

We can’t seem to implement the email validation script on our popups (it works fine on our landing pages, though). I’ve set the script in Script Manager to “Included on All”, which didn’t produce results, and then went into one of the popups and added it manually through the Javascripts feature, again, to no avail.

Any advice?

Userlevel 5

Hey @ArtZ could you include a URL to a page you have this script and popup on?

I can inspect it to confirm the implementation. I just tested in a popup myself and it works. So there may jut be a typo.

Hi Kyle,

Thanks for getting back to me!

Here’s the page - https://miappi.com/. The popup I’m referring to is the one you get after clicking the “Find Out More” CTA in the header. It’s supposed to be filtering out private email domains, but it’s not.

Same as in case of the landing pages, the popups’ form’s email field is set to id: email and I’m using this script before body end tag:

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

<script>
  window.ub.form.customValidators.nonGmail = {
    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>
Userlevel 5

@ArtZ The script isn’t there. Are you sure you published the popup with the script in the popup?

Reply