Go to Home

Form Request on ExpressJS

I recently moved to MERN stack Development from LAMP stack. When I use to build application using the LAMP stack, Laravel had always been my go to choice. It had some great features like migrations, route model binding, validations and much more. As soon as I moved to Node-Express JS, I was badly missing the comfort of Form Request handling from Laravel in Express JS. Hence, I thought of implementing it and explaining how it can be done in Express JS with an example.

Form Validation Package

There are lots of validation packages out there among npm packages. To start with, Joi is widely known and commonly used validation package among Express developers. However, since I was from Laravel world, Joi package seemed a bit complicated for me. So, I was looking for a package which would be easier for people like me to integrate with ease. That's when I found this package called validatorjs. This package is heavily inspired from Laravel Validation and its very easy to integrate.

Installation

You can install validatorjs by

npm install validatorjs

If you're using yarn, then

yarn add validatorjs

Integration

After installing the package, simply create a folder under the app Requests folder like the following and create our first Form Request file.

  • app
    • Requests
      • ProfileRequest.js

Now, let's add the validation rules to the ProfileRequest.js file

Implementation

We have our ProfileRequest.js file ready to be integrated for validation. So, let's add it to our route now like the following

Perfect! Now, we have successfully implemented Form Request on Express JS.

However, if you observe on our Form Request we have scope for improvement. While we develop our application, we might be creating multiple Form Request files, which means we have to repeat lots of code again and again. According to DRY principle, let's extract the common code and keep only the rules on Form Request files. In order to implement that, we have to create a BaseRequest file first.

  • app
    • Requests
      • BaseRequest.js
      • ProfileStore.js

On our BaseRequest.js file, add the following code

Now, let's refactor our ProfileStore.js code

Sweet! We have extracted our validation logic to a separate function called validate and we are defining only the rules on Form Request files. This way, in future if you wanted to change the way error messages are returned, you simply have to edit one file(BaseRequest.js) instead of modifying it on every Form Request file.

See you in another article! Happy Coding!

Few weeks back, I also wrote an article about implementing Laravel like Controllers in Express JS

One email per week. No spam ever.

Subscribe