title: Joi Validation Sequelize Custom Method
body: <p>Im currently trying to validate if the username already exists through Sequelize however currently the promise is returned <strong>AFTER</strong> the response is sent back to the client meaning Joi thinks the username doesnt exist yet every time. Anyone know how to not have Joi just finish validation prematurely and actually process the query/return the right result.</p>
  <p><strong>schema.js</strong></p>
  <pre><code>const Joi = require('joi')
  const { User } = require('../models')
  
  const validateUsername = (value, helpers) =&gt; {
      User.findOne({ where: { username: value } }).then(user =&gt; {
          if (user) {
              return helpers.error('username.exists')
          }
          return value
      })
  }
  
  const schema = Joi.object({
      body: {
          username: Joi.string().min(3).required().custom(validateUsername)
              .messages({
                  'string.base': 'Invalid Username',
                  'string.empty': 'Username Required',
                  'string.min': 'Username Must Be At Least {#limit} Characters Long',
                  'any.required': 'Username Required',
                  'username.exists': 'Username Already In Use'
              })
      }
  })
  
  module.exports = schema
  </code></pre>
  <p><strong>validator.js</strong></p>
  <pre><code>const options = {
      abortEarly: false,
      allowUnknown: true,
      stripUnknown: true
  }
  
  const validator = (schema) =&gt; {
      return (req, res, next) =&gt; {
          const { error } = schema.validate(req, options)
          const valid = error == null
  
          if (valid) {
              next()
          } else {
              const { details } = error;
              const errors = details.map(i =&gt; i.message)
              res.status(422).json({ errors })
          }
      }
  }
  
  module.exports = validator
  </code></pre>