menu

String validation and senitizor for Node.js

Strict validation of incoming data is very essential and expected part of any software system. You must be very sure about the nature of data especially the one which is coming from another source.

We all do validation for simple data like email, name, date of birth etc but while development there are many occurrence where we need to validate other stuff as well ( JSON, Base64,UUID etc).

Node validator :

Chris O’Hara authored this nodejs module which is really very helpful package. This package covers most of the string sanitization and validation. Following are example of some :

isEmailreturns true/false
isURLreturns true/false
isIPreturns true/false
isBase64returns true/false
isFloatreturns true/false
isDivisibleByreturns true/false
isNullreturns true/false
isUUIDreturns true/false
isJSON returns true/false

Some useful sanitization :

toDateConverst to date format.
escapeOften used for SQL queries
toFloatConverts to float

Visit their official Github page and you can see more about it !

Example application :

We are going to build simple node application that consist of form elements such as email,name and at the back-end we will validate the input data coming from forms.

Package.json
{
  "name": "validator-for-node",
  "version": "0.0.1",
  "dependencies": {
    "body-parser": "^1.12.0",
    "express": "^4.12.0",
    "validator": "^3.32.0"
  }
}

Install dependencies by running

npm install

on Terminal or Command prompt.

form.html
<html>
  <head>
    <title>Node validator</title>
  </head>
  <body>
    <form id="main_form" action="validateform" method="post">
      <label>Name :</label><input type="text" name="user_name">
      <label>Email : </label><input type="TEXT" name="email"><br>
      <input type = "submit" value ="Submit">
    </form>
  </body>
</html>

On the form submit action it will redirect to “validateform” and we need to manage this at our Node.js backend. Here is our Server file.

Server.js
var express       =     require("express");
var validation    =     require("validator");
var bodyParser    =     require("body-parser");

var app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/',function(req,res){
    res.sendFile(__dirname + '/form.html');
});

/* Form will redirect here with Input data */
app.post('/validateform',function(req,res){
    if(!validation.isEmail(req.body.email)) {
                //True or false return by this function.
        res.send("Email is Bad");
    } else if(!validation.isAlpha(req.body.user_name)) {
        res.send("Name is Bad");
    } else {
        res.send("Form submitted");
    }
});
app.listen(4000,function(){
    console.log("Listening at PORT 3000");
});

Running the app:

Run this code by typing

node Server.js

on terminal and Visit “localhost:3000” to view the app.

Type some bad email such as without ‘@’ and Name which contains numbers and see the output.

Adding it to Client side:

Download the minified file from here and add it to client side using Script tag. Here is snippet for example purpose.

<script type="text/javascript" src="validator.min.js"></script>
<script type="text/javascript">
  validator.isEmail('[email protected]'); //=> true
  validator.isEmail('shahid - codeforgeek.com'); //=> false
</script>

Conclusion:

The only intention behind this post was to save your time from doing extra and repetitive work of validation of strings and various data. Hope this library help you and save your time and don’t forget to Fork and star the Project.