Form validation in Node.js

We are not covering the installation of Node.js or setup routes

We need to form validation to get user input based on defined form. Server-side validation is must because we never trust the frontend validation. Frontend validation could not work in some cases if the user turned off his client-side JavaScript.

Requirements

Let’s start with a simple validation, for example, we have a form that contains various input fields. Let’s understand with the single field the User Name. We need the username filed that should not be empty and must have characters greater than 2 and less than 30.

First of all install the required Validator package.

npm i validator

Now create a file register.js in /validation folder at your root directory. Open the register.js file and start implementing the validation.

const validator = require('validator');

module.exports = validateRegisterInput = data => {
    let errors = {};

    data.name = typeof data.name === 'string' && data.name.trim().length === 0 ? '' : data.name;

    if(! validator.isLength(data.username, {min: 2, max: 30})) {
        errors.name = 'The User Name must be between 2 and 30 characters';
    }

    if(Validator.isEmpty(data.name)) {
        errors.name = 'The User Name field is required.';
    }

    return {
        errors, 
        isValid: (Object.keys(errors).length == 0 ? true : false)
    }
}

We have created a function validateRegsiterInput that accepts a data object. The data object equals to req.body object. We have defined User Name field with the name username and as you see the codes that we have checked that the field should not empty and should have minimum length 2 and maximum length 30 or whatever you like. At very last we returned the errors and isValid that tells if the validation passes or fails.

Now open your routes file that handled the registration request. Import the defined validation at top and start implementing it.

.....
const validateRegisterInput = require('./validation/register');
.....
.....

router.post('/register', (req, res) => {

    // Make sure the form fields exists
    if(Object.keys(req.body).length === 0) {
        return res.status(400).json({message: 'Please enter the form data!'});
    }

    const {errors, isValid} = validateRegisterInput(req.body);

    // Check Validation
    if(! isValid) {
        return res.status(400).json(errors);
    }

    .......
    .......
});

As you can see on the above code the line that contains the validatateRegisterInput() function.

const {errors, isValid} = validateRegisterInput(req.body);

We have sent the req.body to the validateRegisterInput function and this function returns us two properties i.e. errors and isValid. We can check if the validation passes or not through the isValid property.