DEV Community

Smart Home Dan
Smart Home Dan

Posted on

Express Validator - Do simple if checks to decide what to validate

TLDR: Use a custom validator and extract the core validation rules direct from validator.js

I personally really dislike Express Validator, and have moved onto use alternatives like Joi and Yup. However, often you inherit code that you have to maintain.

Express Validator doesnt make it very clear how to do anything complex. All I wanted to do was check a postcode was valid if a flag was set. E,g,

    {
        "specialFlag": false,
        "postcode": "AB1 1AA"
    }
Enter fullscreen mode Exit fullscreen mode

If special flag was true, we didn't need to check the postcode was a valid one - if it was false, we needed to check. Sounds simple?

The solution is to write a custom validator that you embed as a middleware like this: e.g.

    app.post(
        [
            body.custom(custValFunc),
        ],
        async (req, res....
    )
Enter fullscreen mode Exit fullscreen mode

The custom validator just needed to look like this:

    const custValFunc: CustomValidator = (input: bodyVar): boolean => {
        if (!input.specialFlag) {
            #check if postcode was valid here 
            throw new Error('Postcode isnt valid, but specialFlag isnt set');
        }
        return true;
    }
Enter fullscreen mode Exit fullscreen mode

Seemed easy enough - however I didn't want to write my own validator for post codes, because express validator ships with its own as a middleware - but we cant use those middlewares in the custom validator function! Heres where the pain was - it took me ages to work out how to expose the underlying function.

Turns out express validator just uses validator.js - which will already be installed as a dependancy. We can use the isPostalCode function independantly. So the following code works:

    import { isPostalCode } from 'validator';

    const custValFunc: CustomValidator = (input: bodyVar): boolean => {
        if (!input.specialFlag) {

            if (isPostalCode(input.postcode, 'GB') === false) {  
                throw new Error('Postcode isnt valid, but specialFlag isnt set');
            }
        }
        return true;
    }
Enter fullscreen mode Exit fullscreen mode

This solution works, because if specialFlag is infact set, we skip the post code validation. However if it isn't set - we validate again the proper checks, and can throw a nice error.

You should be able to add your own complex checks and validation rules a bit easier than trying to use the inbuilt express validator functions that don't seem to work in the way you would expect.

Top comments (0)