[英]How to validate whether a username is unique using joi?
As @Ankh already mentioned in the comments, I also think that checking the database isn't joi
's area of responsibility.正如@Ankh 在评论中已经提到的,我也认为检查数据库不是
joi
的职责范围。
However with joi@v16
and any().external()
you can now do an external async validation.但是,使用
joi@v16
和any().external()
您现在可以进行外部异步验证。 This can be used to do a database lookup.这可用于进行数据库查找。 (Details in release document v16 )
(详细信息在发布文档 v16 中)
const lookup = async (id) => {
const user = await db.get('user', id);
if (!user) {
throw new Error('Invalid user id');
}
};
const schema = Joi.string().external(lookup);
await schema.validateAsync('1234abcd');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.