Im new to Mongoose...I have a code snippet below. If I want to check what comes after the @ symbol in an email before I save, how would I do that validation?
var user = new User ({
firstName: String,
lastName: String,
email: String,
regDate: [Date]
});
user.save(function (err) {
if (err) return handleError(err);
})
Validation is defined in the SchemaType. Validation is middleware. Mongoose registers validation as a pre('save') hook on every schema by default. You can disable automatic validation before save by setting the validateBeforeSave option. You can manually run validation using doc.
Mongoose gives us a set of useful built-in validation rules such: Required validator checks if a property is not empty. Numbers have min and max validators. Strings have enum , match , minlength , and maxlength validators.
mongoose-unique-validator is a plugin which adds pre-save validation for unique fields within a Mongoose schema. This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.
You can use a regex. Take a look at this question: Validate email address in JS?
You can try this
user.path('email').validate(function (email) {
var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
return emailRegex.test(email.text); // Assuming email has a text attribute
}, 'The e-mail field cannot be empty.')
Source: Mongoose - validate email syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With