CodexBloom - Programming Q&A Platform

Regex scenarios to Validate Custom Email Formats in JavaScript - implementing Subdomains and TLDs

👀 Views: 49 💬 Answers: 1 📅 Created: 2025-06-11
regex javascript validation JavaScript

I tried several approaches but none seem to work. I'm trying to validate email addresses using regex in a JavaScript application, but I'm running into issues with subdomains and certain top-level domains (TLDs). My current regex is intended to allow for complex emails such as `user@sub.domain.com` and `user@domain.co.uk`, but it seems to unexpected result in certain cases. Here is the regex I've been using: ```javascript const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; ``` When I test it against an email like `user@sub.example.com`, it returns `true`, which is expected. However, it fails for `user@sub.domain.co.uk`, returning `false`. Additionally, I noticed that it does not account for newer TLDs that are longer than three characters, such as `.technology`. I’ve tried modifying the regex to accommodate for the additional TLD lengths by changing the last part to: ```javascript const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; ``` But this still doesn't resolve the scenario with `user@sub.domain.co.uk`. I also considered using a more exhaustive pattern, but that becomes overly complex and may impact performance. Is there a more robust regex that can handle a variety of TLDs while still being performant? Any insights or suggestions would be greatly appreciated! This is part of a larger web app I'm building. The project is a service built with Javascript. Am I approaching this the right way? Is this even possible? I recently upgraded to Javascript latest. Is there a better approach?