gpt4 book ai didi

JavaScript 正则表达式 - 域 URL

转载 作者:行者123 更新时间:2023-12-03 19:00:59 25 4
gpt4 key购买 nike

我有一个包含字段“URL”的表单。第一部分需要用户在文本框中填写。第二部分是预定义的,显示在文本框的右侧。

例如,用户在文本框中输入“test”。第二部分预定义为“.example.com”。因此,总 URL 变为“test.example.com”。

我需要一个正则表达式来验证第一部分。需要满足以下条件:

  1. 不应以连字符开头或结尾

  2. 应该至少包含一个字母

  3. 长度应在 4 到 21 之间

    我使用了正则表达式 /^(?!:\/\/)([a-zA-Z0-9]+\.)?[a-zA-Z0-9][a-zA -Z0-9-]+\.[a-zA-Z]{2,6}?$/I 在此线程中提到:

Javascript regex to match fully qualified domain name, without protocol, optional subdomain

但是这个正则表达式验证了整个 URL(包括第二部分)。我只需要第一部分的验证。

如何修改当前的正则表达式以满足要求?

最佳答案

分解一下。使用正则表达式:

  • /^-|-$/(必须匹配)
  • /[a-z]/i(必须匹配)
  • /^[a-z0-9-]{4,21}$/i(必须匹配)

这样做的好处是您可以向用户提供有意义的错误消息。

document.getElementById('subdomain').addEventListener("input",function() {
var input = this.value;
if( input.match(/^-|-$/)) this.setCustomValidity("Cannot start or end with a hyphen");
else if( !input.match(/[a-z]/i)) this.setCustomValidity("Must contain at least one letter");
else if( !input.match(/^[a-z0-9-]{4,21}$/)) this.setCustomValidity("Must be between 4 and 21 characters long");
// add additional checks here, eg. /^[0-9]/ => Cannot start with a number
else this.setCustomValidity("");
},true);
<form>
<input type="text" id="subdomain" />.example.com
</form>

关于JavaScript 正则表达式 - 域 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47055004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com