简体   繁体   中英

Joi custom validation

I'm using Joi to validate some data from user. I'm using it with module like this:

const Joi = require('joi')

// User validation rules
module.exports = {
  create: {
    body: {
      email: Joi.string().email().required(),
      password: Joi.string().min(6).max(128).required(),
      name: Joi.string().max(128).required()
    }
  },
  update: {
    body: {
      password: Joi.string().min(6).max(128).required(),
      name: Joi.string().max(128).required()
    }
  }
}

and then in router I'm passing it as middleware:

router.post('/register', validator(create), userController.register)

For update I want to create custom validator with code like this:

const json = { 
  "email":"aa@aa.pl",
  "password":"someNewPass",
  "name":"John Smith",
  "activationKey":"123123",
  "active":false,
  "resetPasswordKey":"123123"
}

const forbiddenFields = ["email", "activationKey", "active", "resetPasswordKey"];

const validate = (json, forbidden) => {
  for(let i = 0; i < forbidden.length; i++) {
    if(json.hasOwnProperty(forbidden[i])) {
      return false;
    }
  }
  return true;
}

const isValid = validate(json, forbiddenFields)
console.log('is json valid? ', isValid)

I found extend method in Joi API but example is so confusing that I can not handle to create custom validation with my code.

You may want to use forbidden keys.

 const input = { email: 'example@example.com', activationKey: 123 }; const schema = { email: Joi.string().email(), activationKey: Joi.any().forbidden() }; const result = Joi.validate(input, schema); if (result.error) { console.log(result.error.details) } 
 <script src="https://cdn.jsdelivr.net/npm/joi-browser@13.4.0/dist/joi-browser.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM