Richard Rublev
Richard Rublev

Reputation: 8162

Why User email validation failed? Mongoose ValidationError:

I wanted to extend my UserSchema to validate email

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
    },
    name: {
      type: String,
    },
    email: {
      type: String,
      trim: true,
      required: [true, 'Please add an email'],
      unique: true,
      lowercase: true,
    },

I installed email-validator.

userSchema.path('email').validate((email) => {
  if (!validator.validate('email')) { return false; }
  if (!email) { return false; }
  if (email.length === 0) { return false; }
  return true;
}, 'Email must have a valid format!');

I made a POST request

"username" : "KoleSOmbor",
"name" : "Niki",
"email" : "[email protected]",

Error

POST /api/v1/users 500 18.706 ms - 618
ValidationError: User validation failed: email: Email must have a valid format!

Why?

Upvotes: 0

Views: 268

Answers (1)

Richard Rublev
Richard Rublev

Reputation: 8162

SOLVED

if (!validator.validate(email)) { return false; }

Works fine.

Upvotes: 1

Related Questions