0

How to display a specific error message from a Validation Error. I already display the error with this line of code return res.render("register", {error: err.message}); and show this error ValidationError: User validation failed: email: Email already exists
But it is showing my column field name 'email' and I don't wanna do that. Below is the whole error and I only want to display this message: 'Email already exists'
Ignore the location D: i removed my file directory

    ValidationError: User validation failed: email: Email already exists
    at ValidationError.inspect  
  errors:
   { email:
      { ValidatorError: Email already exists
          at new ValidatorError (D:)
          at validate (D:)
          at D:
          at process._tickCallback (internal/process/next_tick.js:68:7)
        message: 'Email already exists',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'user defined',
        path: 'email',
        value: '[email protected]',
        reason: undefined,
        [Symbol(mongoose:validatorError)]: true } },
  _message: 'User validation failed',
  name: 'ValidationError' }

3 Answers 3

2

To get a specific error message of Validation Error you can use mapped() function like below.

const errors = validationResult(req);
if (!errors.isEmpty()) {
    console.log(errors.mapped().email.msg);
}
Sign up to request clarification or add additional context in comments.

Comments

0

To access nested error message do this err.errors.email.message

Comments

0

Simply create one temp variable and structure your message,

let err_msg = err.errors.email.message;

which will give: 'Email already exists'

You can leave user validation failed message, since same message may be repeated for all validations.

3 Comments

When i add email.message to the err.message it gives me Cannot read property 'message' of undefined
Did try it got undefined.
try to print err object then get towards your email message that should work :) console.log(err); or console.log(JSON.stringify(err)); err{ message: 'er message', email:{ message:' here is the message which you need' } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.