Computer LEGO man

Add email validation to a cloudpage form

We can all agree that spambots are a huge annoyance in the world of subscription sign-up forms, but even worse are failed attempts at real submissions. I’m talking about all the gmail.con addresses that come into your database, immediately bounce, and are therefore useless. These are a huge bummer because they represent people who want your emails but are not going to get them unless they return and sign up again. 

Fortunately, Marketing Cloud has an API that will test email addresses for deliverability, and you can have this API return an error message to the person filling out the form so they can correct their mistakes. Validators include: SyntaxValidator, MXValidator, and ListDetectiveValidator.

SyntaxValidator will let catch the typos, like the dreaded gmail.con.

MXValidator checks whether the email address entered by a user is valid or fake. This will not catch honeypots, which are real, but dormant, email addresses. However, it might stop some spam submissions.

ListDetectiveValidator will let you know that it’s an email address that Ma rketing Cloud will not email. This includes info@ type of email addresses. If someone tries to submit an email like this, you can display a request for a personal email address instead of a catch-all email address. The benefit here is stopping the collection of valid email addresses that Marketing Cloud will refuse to send to and suggest that the subscriber provide a personal email instead.

The first step is to obtain the authorization endpoint, client ID and client secret, which you should store in a data extension, rather than exposing on your CloudPage. You can do a lookup using either AMPScript or SSJS. I have this information stored in a data extension called “keys.” I also use it to store other keys for other API calls. My primary key on this data extension is called Service so that I can easily upsert any changes to this data extension. 

%%[  
  SET @authEndpoint = Lookup("keys","authEndpoint","Service", "SFMC")
  SET @clientId = Lookup("keys","client_id","Service", "SFMC")
  SET @clientSecret = Lookup("keys","client_secret","Service", "SFMC")
]%%
<script runat="server">
     var authEndpoint = Platform.Function.Lookup('keys','authEndpoint','Service','SFMC');
     var clientId = Platform.Function.Lookup('keys','client_id','Service','SFMC');
     var clientSecret = Platform.Function.Lookup('keys','client_secret','Service','SFMC');
</script>

Once you have this information, you can use SSJS to obtain the REST endpoint and an Access Token. You can also store the REST endpoint in the same “keys” data extension. 

You will also need to obtain the email address submitted by the form. Using AMPScript, you can retrieve values posted by a form:

SET @email = RequestParameter("Email_Address")

If you use AMPScript to obtain the authorization endpoint, then you will have to grab those variables as the first step in the SSJS block. You will also need to grab the email variable that was obtained via AMPScript.

var authEndpoint = Variable.GetValue("@authEndpoint");
var clientId = Variable.GetValue("@clientId");
var clientSecret = Variable.GetValue("@clientSecret");

var email = Variable.GetValue("@email");

Once we have all the variables that we need, the first action we will take is obtaining the Access Token and REST endpoint via SSJS:

var payload = {
    client_id: clientId,
    client_secret: clientSecret,
    grant_type: "client_credentials"
  };
  
  var url = authEndpoint + '/v2/token'
  var contentType = 'application/json'
  var accessTokenRequest = HTTP.Post(url, contentType, Stringify(payload));
  if (accessTokenRequest.StatusCode == 200) {
    var tokenResponse = Platform.Function.ParseJSON(accessTokenRequest.Response[0]);
    var mcAccessToken = tokenResponse.access_token
    var rest_instance_url = tokenResponse.rest_instance_url
    };

If the Access Token is returned, then we can move right onto the email validation API:

if (mcAccessToken != null) {
    var headerNames = ["Authorization"];
    var headerValues = ["Bearer " + mcAccessToken];
    var jsonBody = {
      "email": email,
      "validators": [
        "SyntaxValidator",
        "MXValidator",
        "ListDetectiveValidator"
    ]
    }
  };

  var requestUrl = rest_instance_url + "/address/v1/validateEmail";
  var validateEmail = HTTP.Post(requestUrl, contentType, Stringify(jsonBody), headerNames, headerValues);
  
  var aRes = Platform.Function.ParseJSON(validateEmail.Response.toString());
  
  var valid = aRes.valid;
  
  Variable.SetValue("@valid", valid);

The JSON response to tis API call looks like this:

{
 "email": "help@example.com",
 "valid": *false*,
 "failedValidation": "ListDetectiveValidator"
}

So, by parsing the JSON, we are obtaining the “valid” part of the response. We can use the “valid” response for a general error message, or get more granular in the message to the person filling out the form by also grabbing the “failedValidation” part of the response. For example, we can have a message like “please provide a personal email address” when the failedValidation is ListDetectiveValidator. Or, we can have a message like “please check for typos” or “please provide a valid email address” if the failedValidation is the MXValidator or SyntaxValidator. 

We can use AMPScript to modify forms to display an error message for the user filling out the form. For example, I used inline AMPScript to change the placeholder message if the response comes back as not valid. 

<label for="Email_Address">Email Address</label> 
<input id="Email_Address" name="Email_Address" required="" type="email" value="" placeholder="%%=Iif(@valid == 'false','Please enter a valid email address *','Email Address *')=%%">

However, just changing the placeholder text is not enough to really get someone’s attention. You can also use an AMPScript if statement and css to change the color of the placeholder text. Here I am changing the placeholder text to red so that it pops out as a warning. 

%%[if @valid == 'false' then]%%
<style>
input::-webkit-input-placeholder {
color: red !important;
}

input:-moz-placeholder { /* Firefox 18- */
color: red !important;  
}

input::-moz-placeholder {  /* Firefox 19+ */
color: red !important;  
}

input:-ms-input-placeholder {  
color: red !important;  
}
</style>
%%[endif]%%

This, of course, is not a perfect solution, as it does not accommodate color-blind individuals. Another solution to consider is placing javascript in the if statement to displace a window pop-up, such as:

<script>
alert("please enter a valid email address");
</script>

I am sure there are other javascript solutions that you can place use if @valid == ‘false’, but these are just a couple of ideas to get you started.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.