There are a lot of regular expressions for IP address found on the Internet, but we don't see regular expressions with '*'. Usually when we set IP, we will set IP segment (0-255) or use '*' instead.
1. Next is the regular expression without '*'
var checkName = /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9]))$/;
Normal IP address can be verified, such as: 192.168.0.1
2. Next is the regular expression with '*'
var checkName = /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9/*]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9/*]))$/;
The normal IP address can be verified,
For example: 192.168.0.1
192.168.0.*
192.168.*.*
*.*.*.*
3. Multiple groups of IP address verification, used in the middle, separated
Directly available in JQuery Validator
//Detect IP address $.validator.addMethod("checkIp", function (value, element, params) { var checkName = /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9/*]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9/*]))$/; if (value.toString().trim() != value.toString()) { return false; } var ips = value.split(","); return ips.every(value1 => { return (checkName.test(value1)) }); }, "IP Address format error");
Normal use can be modified according to the following
//Target character var checkString = "162.9.6.*,192.186.16.2"; var checkName = /^(?:(?:1[0-9][0-9]\.)|(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:[1-9][0-9]\.)|(?:[0-9/*]\.)){3}(?:(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5])|(?:[1-9][0-9])|(?:[0-9/*]))$/; var ips = checkString.split(","); var result = ips.every(value => { return (checkName.test(value)) }); //Result console.log(result);
4. Another method to verify the number of IP groups (no more than 10 IP groups) is provided
$.validator.addMethod("checkIpLength", function (value, element, params) { var ips = value.split(","); return ips.length > 10 ? false : true; }, "No more than 10 IP paragraph");