Regular expression to validate FQDN in C# and Javascript

戏子无情 提交于 2019-12-01 10:37:37

Generally, the Regular Expressions cookbook is a good source of information, written by two regex experts, so you should be starting there. The solution outlined there is not quite adapted to your needs yet (it doesn't validate an entire string but matches substrings, and it doesn't check for the overall length of the string), so we can modify it a little:

/^(?=.{1,254}$)((?=[a-z0-9-]{1,63}\.)(xn--+)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}$/i

Explanation:

^                      # Start of string
(?=.{1,254}$)          # Assert length of string: 1-254 characters
(                      # Match the following group (domain name segment):
 (?=[a-z0-9-]{1,63}\.) # Assert length of group: 1-63 characters
 (xn--+)?              # Allow punycode notation (at least two dashes)
 [a-z0-9]+             # Match letters/digits
 (-[a-z0-9]+)*         # optionally followed by dash-separated letters/digits
 \.                    # followed by a dot.
)+                     # Repeat this as needed (at least one match is required)
[a-z]{2,63}            # Match the TLD (at least 2 characters)
$                      # End of string
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!