[英]How to validate an ip address with custom format using regular expression
我想用自定義格式驗證IP地址:
我期望的格式: ip address - any value - anynumber
上面的格式分為4部分:
( - )
) 示例: 213.39.59.78 - Public3 address.info - 24
function customFormat(val) { return /^(?=\\d+\\.\\d+\\.\\d+\\.\\d+$)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\.?){4}$/.test(val); } var testFormat = '192.68.35.35'; document.getElementById('regex').innerHTML += testFormat + ' ' + (customFormat(testFormat) ? 'Valid Format!' : 'Invalid Format!');
<ul id="regex"></ul>
上面的代碼從這里開始使用正則表達式,但是只需驗證ip地址即可。
如何驗證我期望的IP地址格式?
您可以嘗試以下方法:
function customFormat(val) { return /^(?=\\d+\\.\\d+\\.\\d+\\.\\d+)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\.?){4} - ((?! -).)+ - \\d{1,3}$/.test(val); } var testFormat = '213.39.59.78 - Public3 address.info - 24'; document.getElementById('regex').innerHTML += testFormat + ' ' + (customFormat(testFormat) ? 'Valid Format!' : 'Invalid Format!');
<ul id="regex"></ul>
正則表達式:
/^(?=\d+\.\d+\.\d+\.\d+)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.?){4} - ((?! -).)+ - \d{1,3}$/
正則表達式包含5個部分,這些部分幾乎與您列出的部分相同:
/^
(?=\\d+\\.\\d+\\.\\d+\\.\\d+)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\.?){4}
-
( - )
) ((?! -).)+
-
為止。 -
( - )
) \\d{1,3}
$/
功能ValidateIPaddress (ipaddress){
if(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)。(25[0-5]|2 [0-4] [0-9] | [01] [0-9] [0-9])(25 [0-5] |?2 [0-4] [0-9] | [01 ?] [0-9] [0-9])(25 [0-5] | 2 [0-4] [0-9] | [01] [0-9] [0-9]? )$ /。test(ipaddress)){
返回(真)
}
alert(“您輸入了無效的IP地址!”)
返回(假)
}
function ValidateIPaddress(ipaddress)
{
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid IP address!")
return (false)
}
通過解析字符串並測試每個部分,您將更容易理解代碼,並能夠根據測試失敗導致的錯誤返回錯誤,例如:
function checkIP(s) { var t = s.split(' - '); // Test number of parts if (t.length != 3) return 'Error: format must be <IP address> - <string, no "-"> - <1 to 3 digits>: ' + s; // Test IP address if (!t[0].split('.').every(v => v >= 0 && v <= 255)) return 'Error: IP address is invalid: ' + t[0]; // Test trailing number if (!/^\\d{1,3}$/.test(t[2])) return 'Error: String must end with 1 to 3 digits: ' + t[2]; // Must be valid return 'Valid string'; } // Some tests ['213.39.59.78 - Public3 address.info - 222', '213.39.59.78 - Public3 address.info - 2222', '213.39.59.78 - Public3 address.info', '213.39.59.788 - Public3 address.info - 222' ].forEach(s => console.log(`Testing "${s}"\\n ${checkIP(s)}`));
您可能要拋出錯誤,而不僅僅是返回帶有錯誤消息的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.