You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript正则表达式:为逗号分隔的邮箱添加单邮箱最大长度50的校验

Fixing Per-Email Length Validation for Comma-Separated Lists

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:

  1. 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.
  2. 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)
  • 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)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:17:32