Skip to main content


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 /^(ra-zA-Z]\d[a-zA-z]\s?\dza-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}(n\-]?\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

It is hidden until the user selects an option from the combo box, but it exists in the Dom


@Kyle.C

I even added another js and has the same problem:

Uncaught TypeError: Cannot read property ‘addEventListener’ of undefined


We’ve been having similar issues with numerous things now.

Main issue has been the custom validation we run for phone numbers from Data8. We get the AddMethod issue on that one. (pretty much the same as @cladius’s original issue)

We also use Selectize.js on some forms which we’ve had to get rid of. I also tried choosen.js which came up with the same error. (both widely recognised jquery plugins) Ended up falling back to vanilla html multi selects for that.

There is definitely some load order issues happening at the moment. Worst thing is that things are changing in the background so one day something breaks, I managed to get it running again, next day a differenent or similar issue starts.


@claudias Adding a 500ms setTimeout fixed a similiar issue for us.


I’ll try it! thanks!


No coding experience here, but wondering if it was possible to exclude all emails from an email form field that are not “.org” or “.edu” email addresses. Anyone have any idea how to do this?


Thank you!


Wondering if anyone has had any luck using this script to validate a URL in a field?


@Mark_Wainwright

I’m experiencing this issue right now. ‘cannot set property myCustomHoneypot of undefined’ . In the console I look for the lp object and it simply isn’t there. What changed?



Same for me


Hi. I need to add custom validation to multiple form fields. Can I do this in one script? And should it be Before Body End Tag?


One of our developers sent us this code for the transitions but I’m not clear on how to incoporate it into this script. Thanks in advance for any help!


//Validating First Name


if( strlen(trim($_POSTS‘first_name’])) > 0 ){

first_name = trim(_POST>‘first_name’]);

if ( $first_name != strip_tags($first_name) ){

array_push($error, ‘First Name do not allow HTML Tags’);

}

}else{

array_push($error, ‘First Name is required’);

}


//Validating Last Name


if( strlen(trim($_POSTs‘last_name’])) > 0){

last_name = trim(_POSTm‘last_name’]);

if ( $last_name != strip_tags($last_name) ){

array_push($error, ‘Last Name do not allow HTML Tags’);

}

}else{

array_push($error, ‘Last Name is required’);

}


//Validating Email Address


if( strlen(trim($_POSTp‘email_address’])) > 0 ){

email = trim(_POSTc‘email_address’]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {

$lead = $enrollment->get_row(“SELECT et_lead_id FROM wp_et_leads where et_lead_email_address=’” . $enrollment->et_open_encrypt(strtolower($email)) . “’”);

//Checking any lead is already registered with this same email id.

if (isset($lead->et_lead_id) && $lead->et_lead_id != ‘’) {

array_push($error, ‘Email address already exist’);

$login = $enrollment->get_row(“SELECT et_short_code_slug FROM wp_et_short_codes where et_short_code_name = ‘ret_show_login_from_mail]’”);

//redirecting to the login page.

if (isset($login->et_short_code_slug) && $login->et_short_code_slug != ‘’) {

header(“Location: " . site_url($login->et_short_code_slug.’/?email=’.$email.’&action=emailexits’));exit;

}else{

header(“Location: " . site_url('login/?email=”’.$email.’”&action=emailexits’));exit;

}

}

}else{

array_push($error, ‘Invalid Email Address’);

}

}else{

array_push($error, ‘Email Address is required’);

}


//Validating Phone Number


if( strlen(trim($_POST ‘phone_number’])) > 0 ){

phone_number = trim(_POSTe‘phone_number’]);

$numStripX = array(’(’, ‘)’, ‘-’, ‘.’, ‘+’,’ ‘);

$numCheck = str_replace($numStripX, ‘’, $phone_number);

$phone_number_int = $numCheck;

$firstNum = substr($numCheck, 0, 1);

$phone_valid = true;

if(($firstNum == 0) || ($firstNum == 1)) {$phone_valid = false;}

else if(!is_numeric($numCheck)){$phone_valid = false;}

else if(strlen($numCheck) > 10){$phone_valid = false;}

else if(strlen($numCheck) < 10){$phone_valid = false;}

else{

$formats = array(’###-###-####’, ‘### ### ####’, ‘(###) (###) (####)’, ‘(###) ###-####’, ‘(###)###-####’,’(###) ### - ####’, ‘##########’, ‘###.###.####’, ‘(###) ###.####’, ‘(###)###.####’);

$format = preg_replace("/<0-9]/", “#”, $phone_number);

if(in_array($format, $formats)){

$phone_valid = true;

}else{

$phone_valid = false;

}

}

if($phone_valid == false){

array_push($error, ‘Invalid Phone Number’);

}

}else{

array_push($error, ‘Phone Number is required’);

}


//Validating Zipcode


if(strlen(trim(_REQUESTb'zip_code'])) > 0){
if(strlen(trim(
_REQUESTo‘zip_code’])) >= 3 ){

zip = trim(_REQUEST/‘zip_code’]);

if(strlen($zip) < 5){

$zip = strlen($zip) == 3 ? (‘00’ . $zip) : (strlen($zip) == 4 ? (‘0’ . $zip) : $zip );

}

$states = $wpdb->get_row(“SELECT zip, state, city, service_status FROM wp_et_states WHERE zip = '” . $zip . “’ LIMIT 1”);

if(empty($states)){

array_push($error, ‘Invalid Zip Code’);

}else{

if($states->service_status < 1){

array_push($error, ‘We’re sorry, CESI does not offer debt management services in your state. Please visit our blog for free financial education and resources.’);

}else{

$state = $states->state;

$city = $states->city;

}

}

}else{

array_push($error, ‘Invalid Zip Code’);

}

}


//Validating State from zipcode


if(strlen(trim($state)) > 0){

if(trim($state) != ‘’) {

$states = $wpdb->get_row(“SELECT et_eligible_states_id,et_eligible_states_status,et_eligible_states_non_eligible_action FROM wp_et_eligible_states WHERE et_eligible_states_name = '” . $state . “’ LIMIT 1”);

if(isset($states) && $states->et_eligible_states_id != ‘’){

if($states->et_eligible_states_status==0 && $states->et_eligible_states_non_eligible_action==‘not-licensed’){

if(!in_array(‘We’re sorry, CESI does not offer debt management services in your state. Please visit our blog for free financial education and resources.’, $error)){

array_push($error, ‘We’re sorry, CESI does not offer debt management services in your state (’.$state.’). Please visit our blog for free financial education and resources.’);

}

}

}else{

if(!in_array(‘We’re sorry, CESI does not offer debt management services in your state. Please visit our blog for free financial education and resources.’, $error)){

array_push($error, ‘We’re sorry, CESI does not offer debt management services in your state (’.$state.’). Please visit our blog for free financial education and resources.’);

}

}

}

}


Hi @KellyCESI,


The code your developer gave you looks like PHP.


You won’t be able to use it directly with your Unbounce landing page. You can only add/edit the front-end part of the page - HTML/CSS/JS.


You have a couple of options:




  1. Host this PHP script on your server and write a JS script that would ping it when a visitor tries to submit the form.




  2. Rewrite the above as a JS script




Best,

Hristian


Thanks, Hristian! Go figure we are speaking 2 languages and I don’t speak either 😉


I let our developer know.


Hi @Johnny_Opao,


Do you have anything similar for Radio Buttons / Checkboxes? I.e. Can you set the “error message” to be triggered if Option A is selected instead of Option B on a certain checkbox in the form? Thanks, Nico


@Mark_Wainwright Thanks for a great solution, but I found an issue and dont know how to fix it.


Trying to implement this on multistep form (Multi-Field, Multi-Step Form 🔥). But validation pops up right in the beginning (even though the validation field is at the end of the multistep form), without letting me to proceed. could you help me out please 🙂


Thanks!



Hi @Hristian,


I’m trying to use the above script to validate two radio buttons on my landing pages form. The radio button options are “YES” and “NO”. I need the lead to click on the “YES” option in order to proceed and successfully click the CTA button, registering with us. However, I’ve tried dozens of variations of the script found on the unbounce community pages but none of them seem to work! I really need some help with this one!!


Hi @nico,


You’ll need to modify both of your scripts - the multi-step and the custom validation to work together.


Best,

Hristian


Hi @Hristian


Thanks for getting back to me. Unfortunately I’m a complete noob at coding with Jquery. Is there anyway I could hire a freelancer to do this for me through the unbounce community?


Cheers,

Nico


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.


Could you give an example of this for a custom message that displays whenever someone selects a “Yes” radio button in a group and shows no message when someone selects the “No” radio button in the same group.


I’m trying to make give a custom message when someone selects “Yes” for each of 2 separate radio button questions.


Claudia me puedes ayudar a generar un script que valide range de 1 a 500? gracias!


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.validationRulese'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.


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}\.30-9]{1,3}\.30-9]{1,3}\.30-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>

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?


Hi @felipe_vimcar - I am trying to implement this but the script to block non work email adresses but it doesn’t seem to register. Do the two bits of script need to be added separately? Thanks


@a.furness

Yep, they need to be added separately!


Reply