Email Validation Before Submitting Realtime Marketing Forms Using Data8

I’ve written about Data8 a few times now (again, not getting paid by them, I just love their service offerings), especially when it comes to how we can do checks on Realtime Marketing forms BEFORE they get submitted in to our database. On the last one, I wrote about doing address auto populate to try and make sure the information provided by those submitting forms is as clean as possible. What about doing the same for email addresses? I checked out the web services page from Data8 to see what other API’s they had, and was happy to see you could check to see if an email address is valid, or check if it is valid and suggest possible corrections too. So I dug in and have a variety of script examples you can use on a Realtime marketing form. See what you think!

First, you can review information about the email validation from Data8. Obviously you will need to sign up and get a paid service (start with a trial) at some point, but you can read through all of their documentation. This link takes you to the email validation page and from there you can go in to the two different methods available.

Click to view in detail

Each page also provided sample code. Looking at the Javascript gave me some ideas of how I could start off.

Click to view in detail

The first thing I tried was the IsValid method which just checks if an email address entered on to your Realtime marketing form is valid. Notice the very bottom of the script where it has YOUR-API-KEY, obviously you need to replace that with your ACTUAL API KEY. 🥰Add the script in the HTML of the form right below the closing </script> tag.

<script>
document.addEventListener('d365mkt-afterformload', function (event) {
    // Load the Data8 Email Validation library
    var data8JsScript = document.createElement('script');
    data8JsScript.onload = function () {
        // Find the email field
        var emailInput = document.querySelector('input[name="emailaddress1"]');
        if (!emailInput) return;

        // Run validation when the field loses focus
        emailInput.addEventListener('blur', function () {
            var email = emailInput.value;
            if (!email) return;

            var emailvalidation = new data8.emailvalidation();

            emailvalidation.isvalid(
                email,
                "Address", // Level: Syntax, MX, Server, Address
                [
                    new data8.option('MissingMXRecordHandling', 'ServerCheck')
                ],
                function (result) {
                    if (!result.Status.Success) {
                        alert("Error: " + result.Status.ErrorMessage);
                        return;
                    }

                    // Handle the validation outcome
                    switch (result.Result) {
                        case "Valid":
                            console.log("Email is valid.");
                            break;
                        case "Invalid":
                            alert("The email address is invalid. Please check and try again.");
                            break;
                        case "Inconclusive":
                            alert("We couldn't validate this email right now. Try again later.");
                            break;
                        case "CatchAll":
                            console.log("Server accepts all emails, so this might not be reliable.");
                            break;
                        case "GreyListed":
                            console.log("Server temporarily refused. Try again in a few minutes.");
                            break;
                    }
                }
            );
        });
    };

    data8JsScript.src = "https://webservices.data-8.co.uk/Javascript/Loader.ashx?key=YOUR-API-KEY&load=EmailValidation";
    document.head.appendChild(data8JsScript);
});
</script>

This creates a pop up notification and states the the email address is invalid (missing an n at the end of my name). Great, it does what it needs to but I am not a fan of the pop up like this, and would rather show the notification on the form itself. I also wanted to check out the Cleanse method from Data8 and see what else I could do.

Click to view in detail

The Cleanse method allows us to pass through additional details about the person so if they are already providing their first and last name and their company name, we could use those to pass through the check. This can aid with suggesting corrections to give better results. For this, we are identifying the fields as variables right at the top to then pass them through back to Data8. Notice the companyInput where the name = organisationname. Company Name as a text field does not exist on the Contact record out of the box, so if you have this, it will be custom. Make sure you replace that with the correct field name from the database. I am also using a level of ‘Address’ to validate the email to. There are several options supported but address does the highest level of checks possible to make sure that the mail server accepts mail for the full email address entered.

<script>
document.addEventListener('d365mkt-afterformload', function (event) {
    var data8JsScript = document.createElement('script');
    data8JsScript.onload = function () {
        var emailInput = document.querySelector('input[name="emailaddress1"]');
        var firstNameInput = document.querySelector('input[name="firstname"]');
        var lastNameInput = document.querySelector('input[name="lastname"]');
        var companyInput = document.querySelector('input[name="organizationname"]');
        var level = "Address";  
        if (!emailInput) return;

        // Message container
        var msg = document.createElement("div");
        msg.classList.add("email-validation-msg");
        emailInput.insertAdjacentElement("afterend", msg);

        // Cleanse function
        function Cleanse(email, level, record) {
            var emailvalidation = new data8.emailvalidation();

            console.log("Sending to Data8:", {
                email: email,
                level: level,
                record: record,
                options: [ new data8.option('MissingMXRecordHandling', 'ServerCheck') ]
            });

            emailvalidation.cleanse(
                email,
                level,
                record,
                [ new data8.option('MissingMXRecordHandling', 'ServerCheck') ],
                showCleanseResult
            );
        }

        // Display API response
function showCleanseResult(result) {
    console.log("Full Data8 response object:", result);

    msg.textContent = ""; // clear previous message

    if (result.Result === "Invalid") {
        msg.textContent = "Please check the address for accuracy. It appears to be invalid.";
    }

}


        // Trigger validation on blur
        emailInput.addEventListener("blur", function () {
            msg.textContent = "";
            var email = emailInput.value;
            if (!email) return;

            var record = {
                companyName: companyInput?.value?.trim() || null,
                name: {
                    forename: firstNameInput?.value?.trim() || "",
                    surname: lastNameInput?.value?.trim() || ""
                }
            };

            Cleanse(email, level, record);
        });
    };

    data8JsScript.src = "https://webservices.data-8.co.uk/Javascript/Loader.ashx?key=YOUR-API-KEY&load=EmailValidation";
    document.head.appendChild(data8JsScript);
});
</script>

You can style the email validation message by adding this to the top of the HTML in the <style> section and change the colour or font size (or whatever you like) as you see fit.

.email-validation-msg {
    color: red;
    font-size: 0.9em;
    margin-top: 5px;
}

Now if someone adds an email address that can’t be found, a message will show directly underneath the email field. The person at this point can still submit the form though, and we aren’t offering up any alternatives.

Click to view in detail

If we use the Cleanse method, we can see what Data8 sends back and any suggested email address they might have provided. The script below does everything that was done with the script above, but this time if a suggested email address is returned, it provides that to the person filling out the form AND gives them an easy way to populate it in to the field just by clicking on it. One thing to keep in mind, the validation is done when the person clicks OUT of the email field. So pay attention to the order of your fields if you are wanting to use the other fields to combine for the check. No point in having someone fill out the email first and the first/last name and company fields are empty.

<script>
document.addEventListener('d365mkt-afterformload', function (event) {
    var data8JsScript = document.createElement('script');
    data8JsScript.onload = function () {
        var emailInput = document.querySelector('input[name="emailaddress1"]');
        var firstNameInput = document.querySelector('input[name="firstname"]');
        var lastNameInput = document.querySelector('input[name="lastname"]');
        var companyInput = document.querySelector('input[name="organizationname"]');
        var level = "Address";  
        if (!emailInput) return;

        // Message container
        var msg = document.createElement("div");
        msg.classList.add("email-validation-msg");
        emailInput.insertAdjacentElement("afterend", msg);

        // Cleanse function
        function Cleanse(email, level, record) {
            var emailvalidation = new data8.emailvalidation();

            console.log("Sending to Data8:", {
                email: email,
                level: level,
                record: record,
                options: [ new data8.option('MissingMXRecordHandling', 'ServerCheck') ]
            });

            emailvalidation.cleanse(
                email,
                level,
                record,
                [ new data8.option('MissingMXRecordHandling', 'ServerCheck') ],
                showCleanseResult
            );
        }

        // Display API response
function showCleanseResult(result) {
    console.log("Full Data8 response object:", result);
    console.log("SuggestedEmailAddress:", result.SuggestedEmailAddress);

    msg.textContent = ""; // clear previous message

    // Case 1: Show warning if invalid
    if (result.Result === "Invalid") {
        msg.textContent = "Please check the address for accuracy. It appears to be invalid.";
    }

    // Case 2: Show suggestion if it exists
    if (result.SuggestedEmailAddress) {
        // Create clickable suggestion link
        var suggestionLink = document.createElement("a");
        suggestionLink.href = "#";
        suggestionLink.textContent = result.SuggestedEmailAddress;
        suggestionLink.addEventListener("click", function(e) {
            e.preventDefault();
            emailInput.value = result.SuggestedEmailAddress;
            msg.textContent = "";
        });

        // Append suggestion to existing message (so warning + suggestion both show)
        if (msg.textContent) {
            msg.appendChild(document.createElement("br")); // line break between warning and suggestion
        }
        msg.appendChild(document.createTextNode("Did you mean "));
        msg.appendChild(suggestionLink);
        msg.appendChild(document.createTextNode("?"));
    }

    // Case 3: API error
    if (!result.Status.Success) {
        msg.textContent = "Error: " + result.Status.ErrorMessage;
    }
}


        // Trigger validation on blur
        emailInput.addEventListener("blur", function () {
            msg.textContent = "";
            var email = emailInput.value;
            if (!email) return;

            var record = {
                companyName: companyInput?.value?.trim() || null,
                name: {
                    forename: firstNameInput?.value?.trim() || "",
                    surname: lastNameInput?.value?.trim() || ""
                }
            };

            Cleanse(email, level, record);
        });
    };

    data8JsScript.src = "https://webservices.data-8.co.uk/Javascript/Loader.ashx?key=YOUR-API-KEY&load=EmailValidation";
    document.head.appendChild(data8JsScript);
});
</script>

Here we can see that the person sees that the email is invalid, AND shows a suggestion. If this is correct, I can just click on it and it will be added to the email field, and then the email will be valid (no error message shown).

Click to view in detail

Final one, if you need/want to be strict and not let the person submit the form if the email address is invalid, we can add in some extra logic to disable the button until a valid email address exists in the email field.

<script>
document.addEventListener('d365mkt-afterformload', function (event) {
    var data8JsScript = document.createElement('script');
    data8JsScript.onload = function () {
        var emailInput = document.querySelector('input[name="emailaddress1"]');
        var firstNameInput = document.querySelector('input[name="firstname"]');
        var lastNameInput = document.querySelector('input[name="lastname"]');
        var companyInput = document.querySelector('input[name="organizationname"]');
        var submitButton = document.querySelector('.submitButton'); // grab button
        var level = "Address";  

        if (!emailInput || !submitButton) return;

        // Message container
        var msg = document.createElement("div");
        msg.classList.add("email-validation-msg");
        emailInput.insertAdjacentElement("afterend", msg);

        // Helper to control button state
// Helper to control button state
function setButtonState(isValid) {
    submitButton.disabled = !isValid;
    submitButton.style.opacity = isValid ? "1" : "0.5";
    submitButton.style.cursor = isValid ? "pointer" : "not-allowed";
    submitButton.title = isValid ? "" : "A valid email address is required";
}


        // Default: disabled until valid
        setButtonState(false);

        // Cleanse function
        function Cleanse(email, level, record) {
            var emailvalidation = new data8.emailvalidation();

            emailvalidation.cleanse(
                email,
                level,
                record,
                [ new data8.option('MissingMXRecordHandling', 'ServerCheck') ],
                showCleanseResult
            );
        }

        // Display API response
        function showCleanseResult(result) {
            msg.textContent = ""; // clear previous message

            if (!result.Status.Success) {
                msg.textContent = "Error: " + result.Status.ErrorMessage;
                setButtonState(false);
                return;
            }

            // Case 1: Invalid
            if (result.Result === "Invalid") {
                msg.textContent = "Please check the address for accuracy. It appears to be invalid.";
                setButtonState(false);
            } else {
                // Valid email
                setButtonState(true);
            }

            // Case 2: Suggestion
            if (result.SuggestedEmailAddress) {
                var suggestionLink = document.createElement("a");
                suggestionLink.href = "#";
                suggestionLink.textContent = result.SuggestedEmailAddress;
                suggestionLink.addEventListener("click", function(e) {
                    e.preventDefault();
                    emailInput.value = result.SuggestedEmailAddress;
                    msg.textContent = "";
                    setButtonState(true); // accept suggestion = valid
                });

                if (msg.textContent) {
                    msg.appendChild(document.createElement("br"));
                }
                msg.appendChild(document.createTextNode("Did you mean "));
                msg.appendChild(suggestionLink);
                msg.appendChild(document.createTextNode("?"));
            }
        }

        // Trigger validation on blur
        emailInput.addEventListener("blur", function () {
            msg.textContent = "";
            var email = emailInput.value;
            if (!email) {
                setButtonState(false);
                return;
            }

            var record = {
                companyName: companyInput?.value?.trim() || null,
                name: {
                    forename: firstNameInput?.value?.trim() || "",
                    surname: lastNameInput?.value?.trim() || ""
                }
            };

            Cleanse(email, level, record);
        });
    };

    data8JsScript.src = "https://webservices.data-8.co.uk/Javascript/Loader.ashx?key=YOUR-API-KEY&load=EmailValidation";
    document.head.appendChild(data8JsScript);
});
</script>

Here we can see that the form shows the email is invalid based on checks using the Name and Company Name, provides a suggestion that can be clicked on AND disables the submit button and has a tool tip stating why it is disabled.

Click to view in detail

Hopefully this gives you a few ideas, and if you use Data8 already you could start implementing something like this on your own Realtime marketing forms in Customer Insights – Journeys. If you aren’t already using Data8, you can contact them here to start a trial or ask them for pricing.

Original Post http://meganvwalker.com/email-validation-before-submitting-using-data8/

0 Votes: 0 Upvotes, 0 Downvotes (0 Points)

Leave a reply

Follow
Search
Popular Now
Loading

Signing-in 3 seconds...

Signing-up 3 seconds...