CodexBloom - Programming Q&A Platform

Regex Not Matching Multiple Email Patterns in JavaScript - Need guide with Edge Cases

πŸ‘€ Views: 34 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
regex javascript email-validation JavaScript

I'm working on a project and hit a roadblock. I'm running into issues with a regex I'm using to validate multiple email formats in my JavaScript application. I'm attempting to match emails that may have subdomains and also allow for optional periods in the local part of the email. My current regex looks like this: ```javascript const emailRegex = /^(?!\.)([\w-\.]+)@([\w-]+\.)+[\w-]{2,}$/; ``` While this regex works for standard emails like `user@example.com`, it fails for emails like `user.name@example.com` and `user@subdomain.example.com`. I also noticed that it incorrectly matches invalid emails like `..user@example.com`. I tried adding additional conditions to handle these cases but ended up with a more complex regex that still didn't pass all my test cases. Here’s my modified attempt: ```javascript const emailRegex = /^(?!\.)([\w-]+\.{0,1}[\w-]+)@([\w-]+\.)+[\w-]{2,}$/; ``` This still does not validate correctly since it accepts `user..name@example.com` as valid. I’m unsure how to properly include the optional periods in the local part without allowing consecutive periods or starting the email with one. Additionally, I want to ensure that subdomains are correctly validated. Can anyone guide to refine this regex to handle these scenarios? I'm using Node.js version 14.17.0 and running this in a simple Express server. Any insights or suggestions would be greatly appreciated! I'm working on a application that needs to handle this. Is there a better approach?