javascript regular expression to check for IP addresses
May be late but, someone could try:
Example of VALID IP address
115.42.150.37192.168.0.1110.234.52.124
Example of INVALID IP address
210.110 – must have 4 octets255 – must have 4 octetsy.y.y.y – only digits are allowed255.0.0.y – only digits are allowed666.10.10.20 – octet number must be between [0-255]4444.11.11.11 – octet number must be between [0-255]33.3333.33.3 – octet number must be between [0-255]
JavaScript code to validate an IP address
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(ipaddress)) { return (true) } alert("You have entered an invalid IP address!") return (false) }
Try this one, it's a shorter version:
^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$
Explained:
^ start of string (?!0) Assume IP cannot start with 0 (?!.*\.$) Make sure string does not end with a dot ( ( 1?\d?\d| A single digit, two digits, or 100-199 25[0-5]| The numbers 250-255 2[0-4]\d The numbers 200-249 ) \.|$ the number must be followed by either a dot or end-of-string - to match the last number ){4} Expect exactly four of these$ end of string
Unit test for a browser's console:
var rx=/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;var valid=['1.2.3.4','11.11.11.11','123.123.123.123','255.250.249.0','1.12.123.255','127.0.0.1','1.0.0.0'];var invalid=['0.1.1.1','01.1.1.1','012.1.1.1','1.2.3.4.','1.2.3\n4','1.2.3.4\n','259.0.0.1','123.','1.2.3.4.5','.1.2.3.4','1,2,3,4','1.2.333.4','1.299.3.4'];valid.forEach(function(s){if (!rx.test(s))console.log('bad valid: '+s);});invalid.forEach(function(s){if (rx.test(s)) console.log('bad invalid: '+s);});