Broad Network


An HTML Form Validation Project with ECMAScript

ECMAScript Validation of HTML Form Data Part 2

Web Development with ECMAScript and MySQL in Node.js

Foreword: In this part of the series I present a project that uses ECMAScript in Node.js, to validate the field values of an HTML Form.

By: Chrysanthus Date Published: 5 Sep 2016

Introduction

This is part 2 of my series, ECMAScript Validation of HTML Form Data. In this part of the series I present a project that uses ECMAScript in Node.js, to validate the field values of an HTML Form. You should have read the previous part of the series before reaching here, as this is a continuation.

Project Description
There is an HTML Form in a web page (from localhost) in a browser. The ECMAScript file to do the validation is in a localhost (personal web server) in the home directory (c:/server). When the ECMAScript file receives the form dataset, it checks if each value of each field has been typed according to the syntax of the data type. If any of the field value is wrongly typed, an error message is sent back to the browser. If all the values are properly typed, a feedback message is sent to the browser indicating so.

The name of the node server file is, server.js;  the name of the validation file is valid.js; both are in the server home directory, c/server. The server file content is given at the bottom of this tutorial.

The HTML Form
The code for the HTML Form page is:

<!DOCTYPE HTML>
<html>
<head>
    <title>Code Sample</title>
</head>
<body>


    <form method="post" action="valid.js">
        <h3>Supplier Info</h3>
        <p>
            <label>Company Name: <input type="text" name="company" id="company"></label>
        </p>
        <p>
            <label>URL: <input type="text" name="url" id="url"></label>
        </p>
        <p>
            <label>Internet IP: <input type="text" name="ip" id="ip"></label>
        </p>
        <p>
            <label>No. of Workers: <input type="text" name="noW" id="noW"></label>
        </p>
        <p>
            <label>Years in Business: <input type="text" name="years" id="years"></label>
        </p>
        <p>
            Service Company? <label>Yes: <input type="radio" name="cType" value=1></label> <label>No: <input type="radio" name="cType" value=0>
        </p>
        <strong>Contact Person</strong><br>
        <p>
            <label>First Name: <input type="text" name="firstname" id="firstname"></label>
        </p>
        <p>
            <label>Last Name: <input type="text" name="lastname" id="lastname"></label>
        </p>
        <p>
            <label>Email: <input type="text" name="email" id="email"></label>
        </p>

        <p>
            <button type="submit">Submit</button>
        </p>

    </form>


</body>
</html>

You should display the page to see what the Form looks like.

The HTTP POST method has been used and the name of the ECMAScript file is, valid.js in the Form action URL of http://localhost/valid.js .

The Data Types Involved
The fields for Company, First name and Last name are of data type text. The field for URL is of data type, URL. The field for Internet IP is of data type IP. The field for Number of Workers is of data type, integer. The field for number of Years in Business, is of data type, float. The field for Service Company (is it a service or a product company) is of data type Boolean. The field for Email is of data type, Email.

ECMAScript Validation Technique
Validation is done using the functions indicated in the previous part of the series. The function may be modified a bit. The text type is validated using ECMAScript regular expression. Use regular expression techniques to validate the text type (company, first name, last name, etc) in ECMAScript.

Coding the ECMAScript Script
The first code segment of the server ECMAScript script is:

exports.valid = function(bodyBytesBuf, callback)
    {
        body = Buffer.concat(bodyBytesBuf).toString();
        body = decodeURIComponent(body);
        body = body.replace(/\+/g, " ");

        keyValueArr = body.split('&');

        keyValueMap = new Map();
        for (item of keyValueArr )
            {
                arr = item.split('=');
                keyValueMap.set(arr[0], arr[1]);
            }

        company = keyValueMap.get('company');
        url = keyValueMap.get('url');
        ip = keyValueMap.get('ip');
        noW = keyValueMap.get('noW');
        years = keyValueMap.get('years');
        cType = keyValueMap.get('cType');
        firstname = keyValueMap.get('firstname');
        lastname = keyValueMap.get('lastname');
        email = keyValueMap.get('email');

        //other code of same function - see below

    }

This code segment assigns the dataset to the variables: company, url, ip, noW, years, cType firstname, lastname and email.

The rest of the code segments are similar to one another in structure. I will just explain one of them:

Validating Number of Workers - Integer
The number of workers has to be an integer. The code to validate this is:

    noW = noW.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces
    noW = Number(noW);

    ret = Number.isInteger(noW);

    if (ret == false)
        {
            callback("Type a whole number for no. of workers!");
            allFine = false;
        }

The datum arrives at the file in the server, as a string. The first line of the code segment removes the leading and trailing spaces. The second line converts the string to a number. The third line returns true if the number is a whole number (integer). The if-construct sends back an arror message to the client, if the number is not an integer.

The complete code of the file, valid.js is:

exports.valid = function(bodyBytesBuf, callback)
    {
        body = Buffer.concat(bodyBytesBuf).toString();
        body = decodeURIComponent(body);
        body = body.replace(/\+/g, " ");

        keyValueArr = body.split('&');

        keyValueMap = new Map();
        for (item of keyValueArr )
            {
                arr = item.split('=');
                keyValueMap.set(arr[0], arr[1]);
            }

        company = keyValueMap.get('company');
        url = keyValueMap.get('url');
        ip = keyValueMap.get('ip');
        noW = keyValueMap.get('noW');
        years = keyValueMap.get('years');
        cType = keyValueMap.get('cType');
        firstname = keyValueMap.get('firstname');
        lastname = keyValueMap.get('lastname');
        email = keyValueMap.get('email');

        var allFine = true;

    //test a company name if it is just text
    company = company.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    function isString(argue)
        {
            if (argue.search(/\D/) != -1)
                {
                    return true;
                }
            else
                {
                    return false;
                }
        }

    if (isString(company) == false)
        {
            callback("The company name has not been typed correctly!");
            allFine = false;
        }

    //test the firstname
    firstname = firstname.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    if (isString(firstname) == false)
        {
            callback("The First Name has not been typed correctly!");
            allFine = false;
        }


    //test the lastname
    lastname = lastname.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    if (isString(firstname) == false)
        {
            callback("The Last Name has not been typed correctly!");
            allFine = false;
        }


    //Test the whole number of workers - integer
    noW = noW.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces
    noW = Number(noW);

    ret = Number.isInteger(noW);

    if (ret == false)
        {
            callback("Type a whole number for no. of workers!");
            allFine = false;
        }


    //Test the float number of Business years
    years = years.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces
    years = Number(years);

    retN = Number.isFinite(years);    //not a very good test for float

    if (retN == false)
        {
            callback("Years in Business e.g. 3 or 3.5 has not been typed correctly!");
            allFine = false;
        }


    //Test the Service Company radio field for true or false.
    cType = cType.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    function istrue(argue)
        {
            if ((argue == undefined)||(argue == null)||(argue == false)||(argue == "")||(argue == 0))
                return false; //for not true
            else
                return true; //for true
        }

    if (istrue(cType) == false)
        {
            callback("You have to answer Yes or No for Service Company!");
            allFine = false;
        }


    //test the email
    email = email.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    function isEmail(argue)
        {
            temp = false;

            if (argue.search(/^[0-9a-zA-Z_\.-]{1,64}@[0-9a-zA-Z_-]{1,252}(\.[0-9a-zA-Z_\-]{2,4}){0,2}$/) != -1)
                {
                    temp = true;
                }

            if (temp == true)
                {
                    if (argue.length <= 254)
                        {
                            return true;
                        }
                    else
                        {
                            return false;
                        }                                    
                }
            else
                {
                    return false;
                }
        }

    if (isEmail(email) == false)
        {
            callback("The Email has not been typed correctly!");
            allFine = false;
        }

    //Test the IP
    ip = ip.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    function isIP(argue)
        {
            if ((argue.search(/^[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}$/) != -1) || (argue.search(/^[\da-fA-F]{1,4}:[\da-fA-F]{1,4}:[\da-fA-F]{1,4}:[\da-fA-F]{1,4}:[\da-fA-F]{1,4}:[\da-fA-F]{1,4}:[\da-fA-F]{1,4}:[\da-fA-F]{1,4}$/) != -1))
                {
                    return true;
                }
            else
                {
                    return false;
                }
        }

    if (isIP(ip) == false)
        {
            callback("The IP address has not been typed correctly!");
            allFine = false;
        }



    //Test the URL
    url = url.replace(/^\s*|\s*$/g, '');  //remove leading and trailing whitespaces

    function isURL(argue)
        {
            if (argue.search(/^http|https:\/\/([0-9a-zA-Z_\-]{1,64}\.)?[0-9a-zA-Z_\-]{1,64}(\.[0-9a-zA-Z_\-]{2,4}){0,2}(:[0-9]{1,5})?(\/[0-9a-zA-Z_\-]{1,64}){0,64}([0-9a-zA-Z_\-]{1,64}(\.[a-zA-Z]{1,4})?)?(#[0-9a-zA-Z_\-]{1,64})?.*/) != -1)
                {
                    return true;
                }
            else
                {
                    return false;
                }
        }

    if (isURL(url) == false)
        {
            callback("The URL has not been typed correctly!");
            allFine = false;
        }


    //All should be well at this point
    //Send positive feedback
    if (allFine == true)
        {
            callback(false, "Information has been sent.");
        }


    }

If all is fine, the dataset (processed) can be sent to an email box or database.

The Server Code
The code for the server file is:

    const http = require('http');
    const valf = require('./valid.js');


    http.createServer(function(request, response)
        {
            var url = request.url;

            const fs = require('fs');

            if (url == '/')
                url = '/server/index.htm';
            else
              url = '/server' + url;


            response.setHeader('Content-Type', 'text/html');


            if (url.search(/.*\.htm\s*$|.*\.html\s*$/i) != -1)
                {
                     fs.readFile(url, (err, data) => {
                         if (err) throw err;

                         output = data.toString('utf8');
                         response.end(output);
                    });
                }


            var body = [];

            request.on('data', function(chunk)
                {
                    body.push(chunk);
                }).on('end', function()
                {
                    if (url.search(/.*valid\.js\s*$/i) != -1)
                        valf.valid(body, function(err, feedback)
                            {
                                if (err)
                                    {
                                         response.end(err);
                                    }
                                 else
                                    {
                                         response.end(feedback);
                                    }

                            });
                    if (url.search(/.*\.gif\s*$|.*\.jpg\s*$/i) != -1)
                        {
                             fs.readFile(url, (err, data) => {
                                     if (err)
                                         throw err;
                                     else
                                         {
                                             matchObj = url.match(/\....\s*$/);
                                             matchStr = matchObj.toString();
                                             ext = matchStr.replace(/\s*/g, '');
                                             ext = ext.replace(/\./, '');
                                             contType = 'image/' + ext;  
                                             response.setHeader('Content-Type', contType);
                                             response.end(data);
                                         }
                                });
                        }


                });


            request.on('error', function(err)
                {
                    // print error to output
                });

            response.on('error', function(err)
                {
                    //send error message to output
                });

        }).listen(8080);

That is it: A project to validate HTML Form data using ECMAScript in Node.js, at the server.

Chrys

Related Links

Web Development Basics with ECMAScript (JavaScript) and MySQL
ECMAScript (JavaScript) Validation of HTML Form Data
Web Live Text Chart Application using ECMAScript (JavaScript) and MySQL
Page Views with Ajax and ECMAScript (JavaScript) and MySQL
Search Within a Site using ECMAScript and MySQL
More Related Links
Node Mailsend with JavaScript
EMySQL API with JavaScript
Node.js Web Development Course with JavaScript
Major in Website Design
Low Level Programming - Writing ECMAScript (JavaScript) Module
ECMAScript (JavaScript) Course

BACK

Comments

Become the Writer's Follower
Send the Writer a Message