I have the following schema with required validations:
var mongoose = require("mongoose");
var validator = require("validator");
var userSchema = new mongoose.Schema(
{
email: {
type: String,
required: [true, "Email is a required field"],
trim: true,
lowercase: true,
unique: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error("Please enter a valid E-mail!");
}
},
},
password: {
type: String,
required: [true, "Password is a required field"],
validate(value) {
if (!validator.isLength(value, { min: 6, max: 1000 })) {
throw Error("Length of the password should be between 6-1000");
}
if (value.toLowerCase().includes("password")) {
throw Error(
'The password should not contain the keyword "password"!'
);
}
},
},
},
{
timestamps: true,
}
);
var User = mongoose.model('User', userSchema);
I pass the email and password through a form by sending post request using the following route:
router.post("/user", async (req, res) => {
try {
var user = new User(req.body);
await user.save();
res.status(200).send(user);
} catch (error) {
res.status(400).send(error);
}
});
module.exports = mongoose.model("User", user);
Whenever I enter a field against the validation rules, I get a very long error message, which is obvious. But now, I want to improve the error handling so that it gets easy to interpret for the users. Rather than redirecting to a generic error page, how can I redirect to the same signup page and display the flash messages near the incorrect fields telling about the error? And also on success, something similar should be done, like a green flash message on the top.
I am using ejs for my signup pages.