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 occurrences 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 :

isEmail returns true/false
isURL returns true/false
isIP returns true/false
isBase64 returns true/false
isFloat returns true/false
isDivisibleBy returns true/false
isNull returns true/false
isUUID returns true/false
isJSON returns true/false

Some useful sanitization :

toDate Converst to date format.
escape Often used for SQL queries
toFloat Converts 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 GitHub 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 helps you and saves your time and don’t forget to Fork and star the Project.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126