APIs & Integrations

Joe_Chen
Member

Integration with JQuery Validator - customized validation

We are trying to integration numverify for customized validation for a field in a form.
The customized validation works in sense of the error message will display if it is invalid. However, this invalid will not prevent a form submission.

We’d like to have existing form behaviour, i.e. the form can not be submitted with a invalid number.

Code snippet for adding the customized validation:

phoneNumberElement.rules(“add”, {
remote: {
url: “http://apilayer.net/api/validate?access_key=” + accessKey + “&country_code=” + countryCode,
type: “GET”,
data: {
number: function () { return phoneNumberElement.val(); }
},
dataFilter: function (response) {
var isValid = false;
if (response) {
var parsedResponse = $.parseJSON(response);
if (parsedResponse.valid) {
isValid = parsedResponse.valid;
}
}

            //if (!isValid) {
            //    form.find("input[type='submit']").prop("disabled", true);
            //} else {
            //    form.find("input[type='submit']").prop("disabled", false);
            //}

            return isValid;
        }
    },
    messages: {
        remote: "Please enter a valid phone number."
    }
});
0 Upvotes
12 Replies 12
CaioSalvador
Participant

Integration with JQuery Validator - customized validation

I have found a workaround for now, I hope it helps someone.

You can prevent the form to be submitted by the click event. Test what you want to test and if is not valid just preventDefault. Ex:

   // Using Jquery
   $('body').on('click', '#formID input[type="submit"]', function(e) {           
       // Your validation Code Here
       if (!formIsValid) {
         e.preventDefault();
       }
   }

This is working for me, for now.

lucabartoli
Member | Diamond Partner
Member | Diamond Partner

Integration with JQuery Validator - customized validation

Have someone found an easy workaround to this?

There is no way to stop the form submission by keypress, so the solution of adding hidden fields solve the issue partially.
Maybe the alternative is to duplicate the form, but it’s necessary to validate the email and phone with the hubspot live validators. Otherwise, there could be validation mismatches.
I don’t think this is a real solution. It’s pretty huge to develop the right way, it’s custom for each form, and this is not in the spirit of this platform.

dan_hmonks
Member

Integration with JQuery Validator - customized validation

Hello, we can build custom field validation and can customise any form elements to our need, we need to take help of javascript or jquery to achieve same. you can make fields hidden and can pass information to these hidden field, by javacript code. We need to append fields inside form using jquery, once user enters information in these appended fields, we can validate and give custom message, once we are through validation, fields information is send to hidden fields.

Let us know if you need any help with a demo.

0 Upvotes
kfischmann1
Member

Integration with JQuery Validator - customized validation

Hi @Joe_Chen,

I’m sheepishly going to have to apologise - I was able to replicate the issue you’re experiencing, and checked in with our Product team who’ve advised that since we updated the form embed functionality some time ago, its essentially not possible to implement custom validation rules; the onFormSubmit callback is executed and the form waits for this to finish, but doesn’t currently take the response into account and continues execution. We removed the previous validation callback functionality as it was creating more issues than it was solving.

To implement custom validation, you’ll need to build the form and associated validation yourself and POST to your own infrastructure, and then push the submission to your HubSpot instance using the Form submission endpoint.

Again, apologies for the misinformation.

0 Upvotes
ron_kagan
Contributor

Integration with JQuery Validator - customized validation

I am working to prevent a form submission of a textarea field that is greater than 255 chars as that breaks the sync with SFDC. Given the info here, it looks as if that may not be possible. Is the onFormSubmit not able to handle this?

hbspt.forms.create({

      portalId: 'XXXXXXX',

      formId: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',

                        onFormSubmit: function($form) {

        $(window).load(function() {

                        $('textarea').keypress(function(){

                            if(this.value.length > 255){

                                return false;

    }

  });

});

}

})

The intent is to stop a the form from submitting if the textarea contains more than 255 chars.

0 Upvotes
Joe_Chen
Member

Integration with JQuery Validator - customized validation

Hi @kfischmann,

Is there no way to stop the form from submitting?

Writing our own form and submit to hubspot endpoint is not an option as we have many forms.

Our goal is to validate phone number, we use numverify API to do the checking. If there is a hubspot way to validate a phone number, we will consider that. I am sure we are not the only client that wants to validate a phone number.

Can you check with your Product team and see if there any possible solution to this please?

kfischmann1
Member

Integration with JQuery Validator - customized validation

Hi @Joe_Chen,

There may possibly be a way to prevent the default behaviour of the form; our embedded forms are now delivered via React.js and this complicates the process somewhat. I’ve tried a couple of mechanisms, but can’t reliably prevent the display of the message after preventing the submission. We tend to shy away from recommending mechanisms that may be implicitly broken - we offer no promises that our embedded form mechanism won’t change in the future.

I checked in with our product team again, and was advised that the solve given prior for building the form manually, processing server side and then pushing the submission via the Form Submission endpoint still stands as our recommended solution.

0 Upvotes
spanishgringo
Participant

Integration with JQuery Validator - customized validation

HubSpot’s recommended solution here does not follow your motto to “solve for the customer”. That recommendation is essentially saying “Tough luck. Go do it all yourself. (as if you were using Eloqua)”.

jonlcrow
Member

Integration with JQuery Validator - customized validation

Hi kfischmann,

We also have a similar problem. Our form validates the email with a confirm email field. Then the email and confirm emails are checked against each other.

Building a manual form for this process is not possible. We purchased HubSpot for the express purpose of not having to involve engineering and development with our marketing practices. To build this form manually would takes months of work on our side of going through the approval process, if we could get it done at all.

If the embed form process is broken then at least provide some simple checks that are done on a majority of forms right now; phone number, email confirmation, these are very common practices.

Can you provide feedback to the product team that this is a completely unacceptable workaround and I look forward to hearing a more appropriate solution soon.

Cheers,
Jonathan

Joe_Chen
Member

Integration with JQuery Validator - customized validation

Hi @kfischmann,

More to the adding customization validation, hubspot’s validation message behaviour does not take into account of the new rules.

0 Upvotes
kfischmann1
Member

Integration with JQuery Validator - customized validation

Hi @Joe_Chen,

The best process to follow here would be to use the onFormSubmit callback within the embed to prevent the submission of the form data to HubSpot on clicking the submit button, then execute your custom validation, then submit the form using form.submit() once validated. I found a good tutorial on how to do this here.

Please also note, that as mentioned in the ‘How to customise the form embed code’ docs;

If you are using jQuery to manipulate the values of form inputs (i.e. using val() or prop()), you must trigger a change event using change() or trigger(‘change’) for the change to properly register.

Let me know how you go with this.

0 Upvotes
Joe_Chen
Member

Integration with JQuery Validator - customized validation

Hi @kfischmann,

I followed the article and I’m still not able to prevent the form submission.

Please see the attached code snippet:
In the code snippet, I use submitHandler to do a preventDetault() and it does not stop the sumission.
I also tried onFormSubmit event of the hubspot form creation.

<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="//cdn2.hubspot.net/hub/1918207/hub_generated/template_assets/1469053091340/custom/page/MyPropertyLife/address-finder.min.js"></script>
<script src="jquery.validate.min.js"></script>
<script>
    hbspt.forms.create({
        css: '',
        portalId: '1918207',
        formId: 'bab58b72-a104-401e-abdf-0f506d6ad458',
        onFormReady: function () {
            initialiseAddressFinder({
                key: "NAXU769PEGC4HWLFVDBY",
                version: "NZ",
                addressFinderElement: "[name='addressfindersearchbox_au']",
                hiddenFieldMappings: {
                    "[name='addressfindersearchbox_au']": "a",
                    "[name='address_finder_nz_region']": "region",
                    "[name='address_finder_nz_city']": "city",
                    "[name='address_finder_nz_suburb']": "suburb",
                    "[name='address_finder_nz_postcode']": "postcode",
                    "[name='address_finder_nz_full_street_address']": "a"
                }
            });
            initialiseNumVerify({
                formElement: "[data-form-id='bab58b72-a104-401e-abdf-0f506d6ad458']",
                accessKey: "6c269b547e77a61026f682662018a485",
                phoneNumberElement: "[name='phone_number_validation_nz']",
                countryCode: "NZ"
            });
        },
        onFormSubmit: function (f) {
            f.submit(function (e) {
                console.log(e, "onFormSubmit");
                e.preventDefault();
                return false;
            });
        },
        target: '#landingpage-address-form-wrapper'
    });

    function initialiseNumVerify(c) {
        var config;

        if (c) {
            config = c;
        }
        else {
            console.log("config is required.");
            return;
        }

        var accessKey = config.accessKey;
        var phoneNumberElementName = config.phoneNumberElement;
        var phoneNumberElement = $(phoneNumberElementName);
        var form = $(config.formElement);
        var countryCode = config.countryCode;

        form.validate({
            onkeyup: false,
            errorPlacement: function (error, element) {
                console.log(error, element);
                $(element).after(error);
            },
            rules: {
                "phone_number_validation_nz": {
                    remote: {
                        url: "http://apilayer.net/api/validate?access_key=" + accessKey + "&country_code=" + countryCode,
                        type: "GET",
                        data: {
                            number: function () { return phoneNumberElement.val(); }
                        },
                        dataFilter: function (response) {
                            var isValid = false;
                            if (response) {
                                var parsedResponse = $.parseJSON(response);
                                if (parsedResponse.valid) {
                                    isValid = parsedResponse.valid;
                                }
                            }

                            return isValid;
                        }
                    }
                }
            },
            messages: {
                "phone_number_validation_nz": {
                    remote: "Please enter a valid phone number."
                }
            },
            submitHandler: function (f, e) {
                f.submit(function (fe) {
                    console.log(fe, "submitHandler");
                    fe.preventDefault();
                    return false;
                });
            }
        });
    }
</script>

<div id="landingpage-address-form-wrapper">
</div>
0 Upvotes