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 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!

Badge

Hi

I’m trying to add a validation message if a certain (hidden) field has a value lower then 5. The value in the hidden field is set automatically if visitors select a picture on my page. The hidden field is ‘havebook’. I read the all above posts and tried to compose a code, but unfortunately it doesn’t work. 

Can anyone help me, please?

 

<script>
  
  lp.jQuery(function($) {
  
    var ruleID = 'custom';
    var field = 'havebook';
    var message = 'Select minimum 5 books';
  
    var rules = module.lp.form.data.validationRules[field];
  
    $.validator.addMethod(ruleID, function(value, field) {
  
      var valid = ( /value >= 5) );
  
      return valid || (!rules.required && !value);
    }, message);
  
    rules[ruleID] = 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!

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?

Bumping this.

Would really like to know how to show a custom alert if a specific radio button is checked!

I only have a very basic knowledge of javascript. How can I get this script to validate a radio button? (If ‘No’ option is checked, an alert message appears)

Digits only isn’t working. Any help?

The digit validation doesn’t seem to be working 😕

Userlevel 5

@ArtZ Well in that case, I have no idea what’s going on haha!
Sounds like a good case for the Unbounce support team.

Hi Kyle. Yup, surprisingly it does work in the preview mode.

Userlevel 5

@ArtZ Does the script work in “preview” mode in the Unbounce builder?

Yup, I’m positive. Here’s the screenshot (added to this popup, then saved and published):

Userlevel 5

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

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

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 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?

@Enayethazari1

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

@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.

Yes, I can help you…

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.

That was it - thanks!!!

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

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?

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>

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.

Reply