Node.js 使用 Joi 实现用户名或邮箱登录验证

在 Node.js 开发中,我们经常使用 Joi 库进行数据验证。本文将介绍如何使用 Joi 实现用户名或邮箱登录验证,并解决 Object schema cannot be a joi schema 错误。

问题描述

我们想要实现一个登录功能,允许用户使用用户名或邮箱登录。但是,如果直接将 Joi schema 对象赋值给另一个 schema 对象,就会遇到 Object schema cannot be a joi schema 错误。

解决方案

我们可以使用 Joi.alternatives().try() 方法来解决这个问题。try() 方法接受多个 schema 作为参数,并尝试依次验证数据。如果其中一个 schema 验证通过,则整个验证通过。

以下代码演示了如何使用 Joi.alternatives().try() 方法实现用户名或邮箱登录验证:

const Joi = require('joi');

const usernameOrEmail = Joi.alternatives().try(
  Joi.string().pattern(/^[A-Za-z0-9\u4E00-\u9FA5\u3040-\u309F\u30A0-\u30FF\u31F0-\u31FF\uAC00-\uD7A3]+$/).min(1).max(50),
  Joi.string().email()
).required();

const password = Joi.string().pattern(/^\S{6,18}$/).required();

exports.login_schema = {
  body: {
    usernameOrEmail,
    password
  }
};

代码解释

  • usernameOrEmail schema 使用 Joi.alternatives().try() 方法,接受两个 schema 作为参数:
    • 第一个 schema 验证用户名,使用正则表达式限制用户名只能包含字母、数字、汉字、日文、韩文;
    • 第二个 schema 验证邮箱,使用 Joi.string().email() 方法。
  • password schema 使用正则表达式限制密码长度为 6-18 位,且不能包含空格。
  • exports.login_schema 对象定义了登录表单数据的验证规则。

总结

通过使用 Joi.alternatives().try() 方法,我们可以轻松实现用户名或邮箱登录验证,并避免 Object schema cannot be a joi schema 错误。'}

Node.js 使用 Joi 实现用户名或邮箱登录验证