Custom Validation in Express.js

From Logic Wiki
Jump to: navigation, search


What you can achieve with custom validation

  • It can be used to verify the existence of the entity in your database.
  • Also to test if a certain value exists in an array, object, string etc.
  • If you want to change the data format itself.

The express-validator library provides a custom method which you can use to do all sorts of custom validations

Implementation of a custom validator uses the chain method .custom(). It takes a validator function.

Custom validators return Promises to show an async validation or throw any value/reject a promise to use a custom error message.

Check if the entity exists in your database

An important one which I use on day to day basis — and I guess you will be using to verify an entity against a database

For example, if someone requests to update their name, you’d use it for a basic PUT request /api/users/:userId.

To make sure that the user should exist in our database, I created a function to check against the DB.

param('userId')
.exists()
.isMongoId()
.custom(val => UserSchema.isValidUser(val))

isValidUser() is a static function which will make an async call to the database and find if the user exists or not.

Let’s write a static function in mongooseSchema:

UserSchema.statics = {
   isValid(id) {
      return this.findById(id)
             .then(result => {
                if (!result) throw new Error('User not found')
      })
   },
}

As we cannot trust the userId sent by the client based on its format only, we need to make sure it is a real account.

Verify against certain values in Array or Object

For example, if you want to apply a rule on a username that it must have a character @.

So in your POST request of user creation or while updating, you can do something like this:

body('username', 'Invalid Username')
.exists()
.isString().isLowercase()
.custom(val => {   
   
   if (val.indexOf('@') !== -1) return true
   return false
}),

Remember: Always return a boolean value from the callback of .custom() function. Otherwise your validation might not work as desired.


Read all from https://medium.freecodecamp.org/how-to-perform-custom-validation-in-your-express-js-app-432eb423510f