Adding custom validation to form fields



Show first post

112 replies

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

I let our developer know.

Userlevel 7
Badge +3

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

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($_POST[‘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($_POST[‘last_name’])) > 0){
last_name = trim(_POST[‘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($_POST[‘email_address’])) > 0 ){
email = trim(_POST[‘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 = ‘[et_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(_POST[‘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(_REQUEST['zip_code'])) > 0){ if(strlen(trim(_REQUEST[‘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.’);
}
}
}
}

Same for me

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

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

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!

I’ll try it! thanks!

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

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.

@Kyle.C
I even added another js and has the same problem:
Uncaught TypeError: Cannot read property ‘addEventListener’ of undefined

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

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.

I’m still getting the same error 😦

Uncaught TypeError: Cannot read property ‘addMethod’ of undefined

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.

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.

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?

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

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.

not working 😦

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?

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!

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

Thanks a lot, Kyle! This would definetly helps!

Reply