mikeerickson / validatorjs

A data validation library in JavaScript for the browser and Node.js, inspired by Laravel's Validator.
https://www.npmjs.com/package/validatorjs
MIT License
1.77k stars 280 forks source link

[HELP] Asynchronous validation #154

Closed rymanalu closed 7 years ago

rymanalu commented 7 years ago

Hi,

I am a Laravel developer and want to try NodeJS. Thanks for creating this cool package! 👍

But I have a question. Currently, I use ExpressJS as the foundation of my web project and validate the data using the middleware.

I create exists rule like in Laravel, but I feels wrong when using it.

This is my sample code:

const Validator = require('validatorjs')

// the middleware
module.exports = (request, response, next) => {
  // check the method and the path before validating...
  if (request.method === 'POST' && request.path === '/users') {
    let rules = {email: 'required|string|exists:users,email'}

    let validation = new Validator(request.body, rules)

    // if I dont use this method, it will not give a response when validation fails...
    validation.fails(() => {
        response.json({message: 'Validation fails'})
    })

    // if I dont use this method, it will not give a response when validation passes...
    validation.passes(() => {
      next()
    })

    // but, if I use fails and passes method, the validator will validate the data twice...

    // use return so it will not call the next...
    return
  }

  next()
}

Can you help me to properly validating the data asynchronously?

garygreen commented 7 years ago

See #155