Skip to the content

Coding Challenges: Answering Frequently Asked Questions

There are many integration methods for Data8’s products and services, some as simple as installing a plugin, and some requiring a more technical implementation such as using our many API’s, or implementing our code libraries. We understand that everyone has different levels of technical ability, and that not everyone is a coding genius. This blog aims to cover some of the most frequently asked questions with our code-based integrations such as using our API’s and our code libraries. If you are still having issues after reading this blog, please get in touch with helpdesk@data-8.co.uk for technical support.

Topics covered:

  • Efficiently using credits
  • Implementing telephone validation through our API
  • Implementing telephone validation through our code library
  • PredictiveAddress custom response handling

  • Efficiently Using Credits

    We get a lot of clients asking why their credit usage is so much higher than the amount of traffic that they are seeing through their website. For example, we often see clients making up to 11 requests per telephone number that is entered on their form. That is one request and therefore one credit for each digit entered! This can be easily reduced to just one call, and still provide validation when the telephone number is entered. A common mistake is to use the “input” event of an input field to trigger a validation call to one of our API’s. As described above, this triggers a request on every single keypress, effectively wasting a whole bunch of credits with each user. A much better approach is to use the “change” event, which is triggered once a user clicks off a field and the value is different to when they started editing it. This will only make one request and still provide the same level of validation, saving you credits and money.


    Implementing Telephone Validation in JavaScript Through Our API

    Using API endpoints allow us to integrate with a wide range of platforms and websites. Data8’s API’s are designed to be user friendly, and easy to use. However, seeing an API and its documentation for the first time can be intimidating and seem like a challenging or impossible task. However, with just a basic coding knowledge, and the help of the code example below, you should be able to get a basic understanding of how API’s can be used, implement an API request in your project and get up and running with our services. Some important things to note, the below code is just sample code and should be tested thoroughly before being used in a production environment. The API key used in the URL of the request will need to be changed to your own Data8 API key generated from the Dashboard of our website.

    <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function(){
            var telInput = document.getElementById("phoneNumber");
            if(telInput)
                telInput.addEventListener("change", function(evt){
                    var telField = evt.target;
                    var phoneNumber = telField.value;
                    if(!phoneNumber)
                        return;
    
                    // Parameters to pass in the body to the API endpoint. 
                    // This is usually the data that you want validating,
                    // and any additional options to customise the functionality.
                    var params = {
                        telephoneNumber: phoneNumber,
                        defaultCountry: "GB",
                        options: {
                            UseLineValidation: true,
                            UseMobileValidation: true
                        }
                    }
    
                    // The url of the API Endpoint. This will be provided in the documentation.
                    // You may need to pass authentication in here such as an API key.
                    var url = "https://webservices.data-8.co.uk/InternationalTelephoneValidation/IsValid.json?key=your-api-key-here";
    
                    var request = new XMLHttpRequest();
                    // Create a new request and specify that it is a POST HTTP request.
                    request.open("POST", url);
                    request.onreadystatechange = function() {
                        if (this.readyState === 4){
                            // Response handling. Ready state of 4 means “DONE” 
                            req.onreadystatechange = null;
                            
                            if(this.status === 200) {
                                // If the request was successful, parse the JSON response
                                // so that we can work with it.
                                var result = JSON.parse(this.response);
                                if (!result.Status.Success ||
                                result.Result.ValidationResult !== "Invalid"){
                                    // Valid number OR the request to our server failed 
                                    // i.e. no credits
                                    telField.setCustomValidity("");
                                    telField.classList.remove("data8Error");
                                }
                                else{
                                    // Invalid number
                                    telField.setCustomValidity("Phone number is invalid");
                                    telField.classList.add("data8Error");
                                }
    
                                telField.reportValidity();
                            }
                            else
                                alert(request.responseText);
                        }
                    };
                    
                    request.send(JSON.stringify(params));
                });
        });
    </script>
    

    Implementing Telephone Validation Through Our JavaScript Code Library

    Take a basic HTML page, such as the below code, which could represent the form on your website containing an email and phone field.

    <head>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    </head>
    <body>
    <form id="myForm">
        <input type="tel" name="telephone" class="required" />
        <input type="email" name="email" class="required" />
        <input type="submit" id="submitButton"/>
    </form>
    </body>
    

    To integrate Data8 email and international telephone validation using the jQuery code library (https://www.data-8.co.uk/resources/code-samples/jquery-telephone-email-validation/), we would simply add the required scripts, and add the classes “d8val_email” and “d8val_inttelphone” to the appropriate input fields. For example, the above code would become:

    <head>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script type="text/javascript" src="https://webservices.data-8.co.uk/javascript/loader.ashx?key=your-api-key&load=InternationalTelephoneValidation,EmailValidation"></script>
        <script type="text/javascript" src="https://webservices.data-8.co.uk/javascript/jqueryvalidation_min.js"></script>
    </head>
    <body>
    <form id="myForm">
        <input type="tel" name="telephone" class="required d8val_inttelephone" />
        <input type="email" name="email" class="required d8val_email" />
        <input type="submit" id="submitButton"/>
    </form>
    </body>
    

    Furthermore, to extend the telephone validation service to make use of the mobile and landline validation options, we would just alter the class on the telephone field to “d8val_inttelephone_mobile_line” like so: <input type="tel" name="telephone" class="required d8val_inttelephone_mobile_line" />

    We can use the standard jQuery validation functionality to extend the service to use advanced configuration options, as seen below. Notice the change in class name on the telephone field, adding “_opt” to specify that we want to use custom options. We can then set these options in the validate function.

    <body>
    <form id="myForm">
        <input type="tel" name="telephone" class="required d8val_inttelephone_mobile_line_opt" />
        <input type="email" name="email" class="required d8val_email" />
        <input type="submit" id="submitButton"/>
    </form>
    <script type="text/javascript">
        $("#myForm").validate({
            rules: {
              telephone: {
                required: "Enter a telephone number",
                d8val_inttelephone_opt: [ { name: "RequiredCountry", value: "44" } ]
              }
            }
          });
    </script>
    </body>
    

    PredictiveAddress Custom Response Handling

    Another popular question that we get from clients using our address capture service, PredictiveAddress, is ‘How can we use the returned address like this...’. Our PredictiveAddress service comes with a bunch of configuration options that allow users to customise the address lookup service to suit their needs. Whether that is to limit available countries, change the formatting of the returned address or to use the returned address in whatever way they wish. Documentation for the PredictiveAddress service can be found here: https://www.data-8.co.uk/resources/code-samples/predictiveaddress/#AdvancedOptions Below is some sample code that contains the “allowedCountries” option which restricts the PredictiveAddress lookup service to specific countries. The “fields” option is used to map the appropriate fields to the returned address fields. For example, to put the returned city in the city field on your form. The code also makes use of the “selectAddress” option, which is a callback function for when an address is selected. This option can be used to manipulate the returned address however you wish and can be used in conjunction with the “fields” option to automatically populate the appropriate fields on the form and then do a custom action afterwards.

    <head>
        <script type="text/javascript" src="https://webservices.data-8.co.uk/javascript/predictiveaddress.js"></script>
        <link rel="stylesheet" href="https://webservices.data-8.co.uk/content/predictiveaddress.css" />
    </head>
    <body>
        <form>
            <input type="text" id="address1" name="address1" />
            <input type="text" name="address2" />
            <input type="text" name="city" />
            <input type="text" name="county" />
            <input type="text" name="postcode" />
            <select name="country" >
                <option value="GB">United Kingdom</option>
                <option value="US">United States</option>
            </select>        
        </form>
    
        <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", function(){
                var txt = document.getElementById('address1');
                new data8.predictiveaddressui(txt, {
                // Change this to your own API Key
                ajaxKey: 'your-api-key',
                fields: [
                    { element: 'address1', field: 'line1' },
                    { element: 'address2', field: 'line2' },
                    { element: 'city', field: 'town' },
                    { element: 'county', field: 'county' },
                    { element: 'postcode', field: 'postcode' },
                    { element: 'country', field: 'country' }
                ],
                allowedCountries: [ 'GB', 'US' ],
                selectAddress: function(returnedAddress, returnedCountry){
                    // this is the callback function for when an address is selected
                    // you can manipulate the returned address as you wish here.
                    
                    // the fields option above will be used to populate the specified fields with
                    // data before this function is called.
    
                    // returnedAddress contains both the formatted and raw versions of the address
                    var formattedAddress = returnedAddress.Address.Lines;
                    var oneLineAddress = formattedAddress.join(" > ");
                    // oneLineAddress would now be like Data8 > Unit 4 > Venture point and so on..
                }
                });
            });
        </script>
    </body>
    

    Thanks for reading the blog. If you need any more technical help or assistance, please don’t hesitate to contact our helpdesk team by email at helpdesk@data-8.co.uk.

    Next Steps

    Find out more about how Data8 can help you

    About the author

    Ryan Lewis

    Ryan Lewis