Search code examples
node.jsexpressexpress-validator

express-validator use custom validator in validation schema


I'm trying to use custom validator in my validation schema as an object that takes a function but it's not working, it returns back with an error that says: this.validator is not a function but not the message i've put when throwing the error in the function

  email: {
    isLength: {
      options: {
        max: 40,
      },
      errorMessage: "Email must be between 5 and 15 characters in length",
    },
    notEmpty: {
      errorMessage: "Email must not be empty.",
    },
    isEmail: {
      errorMessage: "Invalid email.",
    },
    isString: {
      errorMessage: "Email must be a string.",
    },
    custom: async (email, { res }) => {
      const isExist = await fetchUserByEmailOrID(email);
      if (isExist.length) {
        throw new Error("A user already exists with this e-mail address");
      }
    },
  },

Signup controller method:

  signup: async (req, res, next) => {
    const result = validationResult(req);
    if (!result.errors.length == 0) {
      return res.status(400).json({
        status: 400,
        message: result.errors,
      });
    }
    const { firstName, lastName, email, password, gender, birthDate, image } =
      matchedData(req);

    const saltRounds = 10;
    const hashPassword = await bcrypt.hash(password, saltRounds);
    await DB.execute(
      "INSERT INTO `users` (`firstName`,`lastName`,`email`,`gender`,`birth_date`,`image`,`password`,`status`, `isAdmin`) VALUES (?,?,?,?,?,?,?,?,?)",
      [
        firstName,
        lastName,
        email,
        gender,
        birthDate,
        image,
        hashPassword,
        "pending",
        0,
      ]
    );
    res.status(201).json({
      status: 201,
      message: "Registeration process has been submitted",
    });
  },

Solution

  • You need to put the custom validator function under options property (email.custom.options)

    Docs

    email: {
        isLength: {
            options: {
            max: 40,
            },
            errorMessage: "Email must be between 5 and 15 characters in length",
        },
        notEmpty: {
            errorMessage: "Email must not be empty.",
        },
        isEmail: {
            errorMessage: "Invalid email.",
        },
        isString: {
            errorMessage: "Email must be a string.",
        },
        custom: {
            options : async (email) => {
                const isExist = await fetchUserByEmailOrID(email);
                if (isExist.length) {
                    throw new Error("A user already exists with this e-mail address");
                }
            },
            bail: true
        }
    }