【问题标题】:Apply url validation regex on comma separated list在逗号分隔列表上应用 url 验证正则表达式
【发布时间】:2019-05-03 14:04:59
【问题描述】:

我正在尝试使用下面的正则表达式进行 url 验证。

/^((((.*):\/\/)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';\/?:@&=+$,A-Za-z0-9])+)([).!';\/?:,][[:blank:]])?$/i.test( value );

当我提供一个 URL 时,它会按预期工作。我的输入将包含多个以逗号分隔的 URL,我想将上述正则表达式应用于逗号分隔列表中的所有单个 URL。我还想防止在 URL 中使用某些字符串(例如“名称”、“城市”等)

例如

我需要对我的正则表达式进行哪些更改才能达到上述结果?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    由于您的正则表达式适用于单个 url,因此您可以使用 splitevery 的组合使其适用于列表。下面是我的解决方案:

    const isClean = str => ["name", "city"].every(word => !str.includes(word));
    const isValid = input =>
      input
        .split(",")
        .every(
          value =>
            /^((((.*):\/\/)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$/i.test(
              value
            ) && isClean(value)
        );
    
    console.log(isValid("http://localhost:8080")); // true
    console.log(isValid("https://something.com")); // true
    console.log(isValid("http://localhost:8080,something.com,something2.com")); // false
    console.log(isValid("http://localhost:8080,http://something.com,http://something2.com")); // true
    console.log(isValid("http://name.com")); // false
    console.log(isValid("http://city.com")); // false
    

    Run on CodeSandbox

    【讨论】:

      猜你喜欢
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      相关资源
      最近更新 更多