Express Custom Validator always returning Error

Issue

This is part of my login API used to validate the new user details. The function ifIDAlreadyExist checks the DB and returns true/false for exists/not exists respectively.

Even when the result is false, the error message is returned with the below code. What’s wrong with this?

const RegInputValdiationRules = () => {
  return [
    check("id")
      .not()
      .isEmpty()
      .withMessage("Please enter the login id")
      .custom((value) => {
        ifIDAlreadyExist(value).then((exists) => {
          console.log(exists);
          if (exists === true) return Promise.reject("");
          else return true;
        });
      })
      .withMessage("ID already exists"),
    check("password")
      .not()
      .isEmpty()
      .isLength({ min: 6 })
      .withMessage("Password should contain at least six characters"),
  ];
};

enter image description here

Solution

you’re missing return within custom method:

const RegInputValdiationRules = () => {
  return [
    check("id")
      .not()
      .isEmpty()
      .withMessage("Please enter the login id")
      .custom((value) => {
        return ifIDAlreadyExist(value).then((exists) => {
          console.log(exists);
          if (exists === true) return Promise.reject("");
          else return true;
        });
      })
      .withMessage("ID already exists"),
    check("password")
      .not()
      .isEmpty()
      .isLength({ min: 6 })
      .withMessage("Password should contain at least six characters"),
  ];
};

Answered By – traynor

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published