Javascript 如何使用正则表达式验证域名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26093545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate domain name using regex?
提问by PNG
This is my code for validating domain name.
这是我验证域名的代码。
function frmValidate() {
var val = document.frmDomin;
if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/.test(val.name.value)) {
}
else {
alert("Enter Valid Domain Name");
val.name.focus();
return false;
}
}
and
和
<form name="frmDomin" action="" method="post" onsubmit="return frmValidate();">
Domain Name : <input type="text" value="" id="name" name="name" />
</form>
Now I entered http://devp1.tech.inand it alert the message. I want to enter sub domain also. How to change this? I should not get alert.
现在我输入了http://devp1.tech.in它并提醒消息。我也想进入子域。如何改变这个?我不应该警觉。
回答by élektra
This is a little on the heavy side:
这有点沉重:
^(?:(?:(?:[a-zA-z\-]+)\:\/{1,3})?(?:[a-zA-Z0-9])(?:[a-zA-Z0-9-\.]){1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+|\[(?:(?:(?:[a-fA-F0-9]){1,4})(?::(?:[a-fA-F0-9]){1,4}){7}|::1|::)\]|(?:(?:[0-9]{1,3})(?:\.[0-9]{1,3}){3}))(?:\:[0-9]{1,5})?$
Will match:
将匹配:
google.comdb.my-website.co.usftp://container-617.databases.onlinemany-ports.com:7777localhost
google.comdb.my-website.co.usftp://container-617.databases.onlinemany-ports.com:7777localhost
IPv4
IPv4
192.168.3.1127.0.0.1:3306
192.168.3.1127.0.0.1:3306
IPv6 (partial support)
IPv6(部分支持)
[2001:0db8:85a3:0000:0000:8a2e:0370:7334][2001:db8:85a3:0:0:8a2e:370:7334](same as previous)[da7a:ba5e:da7a:ba5e:da7a:ba5e:da7a:ba5e]:3306[::1](localhost loopback)[::](unspecified address)
[2001:0db8:85a3:0000:0000:8a2e:0370:7334][2001:db8:85a3:0:0:8a2e:370:7334](和之前一样)[da7a:ba5e:da7a:ba5e:da7a:ba5e:da7a:ba5e]:3306[::1](本地主机环回)[::](未指定地址)
But not (IPv6)
但不是(IPv6)
- [
2001:db8:85a3::8a2e:370:7334]
- [
2001:db8:85a3::8a2e:370:7334]
This regular expression does not support collapsing consecutive 0-segments into a '::' in IPv6 addresses. (read: don't try this on IPv6 addresses)
此正则表达式不支持将连续的 0 段折叠为 IPv6 地址中的“::”。(阅读:不要在 IPv6 地址上尝试此操作)
回答by Mogli
Try this regex:
试试这个正则表达式:
/([a-z0-9]+\.)*[a-z0-9]+\.[a-z]+/
回答by Sodium
<script>
function frmValidate() {
var val = document.frmDomin.name.value;
if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(val)) {
alert("Valid Domain Name");
return true;
} else {
alert("Enter Valid Domain Name");
val.name.focus();
return false;
}
}
</script>
Note : This will not validate Url.
注意:这不会验证 Url。

