JavaScript正则表达式:为逗号分隔的邮箱添加单邮箱最大长度50的校验
Got it, let's break down why your original solution wasn't working and how to fix it properly.
The Problem with Your Current Approach
Your initial regex (?!.{51}) checks if the entire input string is longer than 50 characters, which works for single emails but fails for comma-separated lists—it blocks any list where the total length exceeds 50, even if every individual email is under the limit. We need to apply the 50-character restriction to each email in the list, not the whole string.
The Solution: Local Length Validation for Each Email
We'll modify the single email regex to include a forward lookahead that only checks the length of the current email (the part between commas or the start/end of the string). Here's how:
Updated Single Email Regex
This regex ensures the current email (from the current position to the next comma or end of string) is between 1-50 characters, while maintaining your original email format rules:const VALID_EMAIL = /(?=(?:[^,]|$){1,50})[a-z0-9-_.+]+@[a-z0-9]+[a-z0-9-.]*\.[a-z0-9]{2,9}/i;(?=(?:[^,]|$){1,50}): Forward lookahead that verifies the sequence from the current position (either the start of the string or right after a comma) to the next comma or end of the string is 1-50 characters long.- The rest of the regex keeps your original email format validation.
Comma-Separated List Regex
Use the updated single email regex to build your list validator as before:const COMMA_SEPARATED_EMAILS = new RegExp(`^(?:${VALID_EMAIL.source}(?:, *)?)+$`, 'i');
Test Cases to Verify
- Valid Inputs
- Single short email:
john.doe@example.com(length 19, passes) - Multiple valid emails:
alice@test.co, bob_smith+tag@sub.domain.org(each email is under 50 characters)
- Single short email:
- Invalid Inputs
- Single over-length email:
this-is-an-extremely-long-email-address-that-exceeds-fifty-characters@example.com(length >50, fails) - List with one over-length email:
short@test.com, way-too-long-email-that-goes-past-fifty-characters@big-domain.com(second email is over 50, fails)
- Single over-length email:
Extra Notes
- If you want to allow optional whitespace around emails (e.g.,
email1@test.com , email2@test.com), adjust the single email regex to include\s*around the email pattern. If you want to exclude whitespace from the 50-character count, a simpler approach is to split the input by commas, trim each email, then validate both length and format separately for each entry.
内容的提问来源于stack exchange,提问作者heisenberg7584

