NodeJS joi验证不能区分大小写

of1yzvn4  于 2023-03-22  发布在  Node.js
关注(0)|答案(1)|浏览(154)

我正在使用joi验证,如下所示。但是在测试过程中,它不能区分大小写。如果我为userId输入“test”或“TEST”,它会返回同样的结果,这是不应该的。你能给予我一些提示吗?

const SignupRepository = require('../repositories/signup.repository');
const { ValidationError } = require('../exceptions/index.exception');
const {
  createHashPassword,
  comparePassword,
} = require('../modules/cryptoUtils.js');

const Joi = require('joi');
const re_userId = /^[a-zA-Z0-9]{3,10}$/i;
const re_nickname = /^[a-zA-Z0-9]{3,10}$/;
const re_password = /^[a-zA-Z0-9]{4,30}$/;

const userSchema = Joi.object({
  userId: Joi.string().pattern(re_userId).required(),
  nickname: Joi.string().pattern(re_nickname).required(),
  password: Joi.string().pattern(re_password).required(),
});

class SignupService {
  constructor() {
    this.signupRepository = new SignupRepository();
  }

  isIDDuple = async (userId) => {
    const lowercaseUserId = userId.toLowerCase();
    await userSchema.validate({ userId });

    const existingUser = await this.signupRepository.isIDDuple(userId);
    if (existingUser.length) {
      throw new ValidationError('ID is already taken');
    }
    return { success: true, message: 'available ID' }
  };

  isNicknameDuple = async (nickname) => {
    await userSchema.validate({ nickname });

    const existingUser = await this.signupRepository.isNicknameDuple(nickname);
    if (existingUser.length) {
      throw new ValidationError('Nickname already taken');
    }
    return { success: true, message: 'Nickname available' }
  };

  userSignup = async (userId, password, nickname) => {

 try{
      const lowercaseUserId = userId.toLowerCase(); // Convert to lowercase
      await userSchema.validate({ userId, password, nickname }); // Validate lowercase user ID

      const existingUser = await this.signupRepository.findByID(userId);

      if (existingUser.length) {
        throw new ValidationError('ID already taken');
      }

      const existingUser2 = await this.signupRepository.findBynickname(nickname);
      if (existingUser2.length) {
        throw new ValidationError('Nickname already taken');
      }

      
      const hashedPassword = await createHashPassword(password);

      const user = await this.signupRepository.userSignup(
        userId,
        hashedPassword,
        nickname
      );

      return { success: true, message: 'successfully registered' };

  } catch (error) {
    if (error instanceof ValidationError) {
      throw error;
    } else {
      throw new Error('wrong format');
    }
  }
}

}
module.exports = SignupService;

我试过不敏感和转换所有小写之前去数据库。但没有工作

8yoxcaq7

8yoxcaq71#

对于/^[a-zA-Z0-9]{3,10}$/i,如果字符串包含3到10个字符、大小写字母、0到9的数字,则该字符串有效
/i参数指示忽略大小写,因此/^[a-zA-Z0-9]{3,10}$/i等于/^[a-z0-9]{3,10}$/i/^[A-Z0-9]{3,10}$/i
/^[a-zA-Z0-9]{3,10}$ - Test1:有效,test1:有效,Test1%:无效,原因是%
/^[a-z0-9]{3,10}$ - test1:有效,Test1:测试无效
/^[A-Z0-9]{3,10}$ - Test1:有效,test1:试验无效

相关问题