Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I have a mongoose schema for users (UserSchema) and I'd like to authenticate whether the email has the right syntax. The validation that I am currently using is as follows:

UserSchema.path('email').validate(function (email) {

  return email.length

}, 'The e-mail field cannot be empty.')

However, the above command only checks if the field is empty or not, and not for the syntax.

Does something previously exist that I could re-use or would I have to come up with my method and call that inside the validate function?

1 Answer

0 votes
by (108k points)
edited by

You can simply use a regex. 

UserSchema.path('email').validate(function (email) {

   var emailRegex12321 = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

   return emailRegex12321.test(email.text); // Assuming email has a text attribute

}, 'The e-mail field cannot be empty.')

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 14, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Feb 16, 2020 in Web Technology by ashely (50.2k points)

Browse Categories

...