javascript regular expression to check for IP addresses

144,790

Solution 1

The regex you've got already has several problems:

Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.

Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.

This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:

if(block >= 0 && block <= 255) {....}

Hope that helps.

Solution 2

May be late but, someone could try:

Example of VALID IP address

115.42.150.37
192.168.0.1
110.234.52.124

Example of INVALID IP address

210.110 – must have 4 octets
255 – must have 4 octets
y.y.y.y – only digits are allowed
255.0.0.y – only digits are allowed
666.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)  
}  

Solution 3

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);});

Solution 4

If you are using nodejs try:

require('net').isIP('10.0.0.1')

doc net.isIP()

Solution 5

Don't write your own regex or copy paste! You probably won't cover all edge ceses (IPv6, but also octal IPs, etc). Use the is-ip package from npm:

var isIp = require('is-ip');

isIp('192.168.0.1');

isIp('1:2:3:4:5:6:7:8');

Will return a Boolean.

Downvoters: care to explain why using an actively maintained library is better than copy pasting from a website?

Share:
144,790
KennC.
Author by

KennC.

Just a student trying to do what's required of him.

Updated on July 05, 2022

Comments

  • KennC.
    KennC. almost 2 years

    I have several ip addresses like:

    1. 115.42.150.37
    2. 115.42.150.38
    3. 115.42.150.50

    What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.150.* (I will be able to search for all 3 ip addresses)

    What I can do now is something like: /[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/ but it can't seems to work well.

    Thanks.

  • framp
    framp about 11 years
    /^(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('10.10.10.10')
  • Alvaro Flaño Larrondo
    Alvaro Flaño Larrondo over 9 years
    The IP 200sd.100f.85.200(V) (or any with letters in it) is returning true in your function. Just check also if !isNaN(block) on each block to avoid this. Nice funtion BTW. return !isNaN(block) && parseInt(block,10) >=0 && parseInt(block,10) <= 255;
  • SpaceNinja
    SpaceNinja about 9 years
    This worked great, I appreciate you putting in a whole function and examples of what will/will not pass.
  • Dan K.K.
    Dan K.K. over 8 years
    0.0.0.0 is assumed to be valid
  • oriadam
    oriadam over 8 years
    In that case you can omit the negative look-ahead (?!0)
  • anhldbk
    anhldbk about 8 years
    I think the function should be implemented as: function isIPv4Address(entry) { var blocks = entry.split("."); if(blocks.length === 4) { return blocks.every(function(block) { const value = parseInt(block, 10); if(value >= 0 && value <= 255){ var i = block.length; while (i--) { if(block[i] < '0' || block[i] > '9'){ return false; } } return true; } }); } return false; }
  • Dave Yarwood
    Dave Yarwood about 8 years
    This is a great answer IMHO. Not trying to do too much with regex is generally a good practice. Compare this answer to the other answers and think about which one produces the most readable/intuitive code. More readable code takes less time to understand and is less error-prone.
  • Dave Yarwood
    Dave Yarwood about 8 years
    One nitpick: Shouldn't it be block >= 0 ?
  • omni
    omni over 7 years
    OP is asking for a valid JS solution. You just assume npm is available.
  • mikemaccana
    mikemaccana over 7 years
    @masi where would npm not be available?
  • TWright
    TWright over 7 years
    Your regex was the only one I could get to pass my tests. Thanks!
  • ErickBest
    ErickBest about 7 years
    Glad I could help. Enjoy Coding!!
  • Adam Parkin
    Adam Parkin about 6 years
    Note fails if alphabetical char appears in a part as parseInt("2a00", 10) returns 2 and not NaN, so an ip of 200.200.2a00.200 ends up being accepted as valid when it's not.
  • Adam Parkin
    Adam Parkin about 6 years
    Will fail if ip is undefined or if it's an integer.
  • Dave Joyce
    Dave Joyce about 6 years
    Thanks Adam, modified code to look at both parseInt and original num by adding isNaN(num)
  • migueloop
    migueloop about 6 years
    What about allowing subnets? pe: 192.168.1.10/24
  • oriadam
    oriadam about 6 years
    @migueloop I didnt try it: ^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}(\/\d+)?‌​$
  • Patrick Wozniak
    Patrick Wozniak over 5 years
    @DaveYarwood: A ip address cannot be greater than 255.
  • Dave Yarwood
    Dave Yarwood over 5 years
    Right, I just meant shouldn't it be >= instead of >? Because 0 is a valid block value.
  • vikyd
    vikyd over 5 years
    Visualization of @ErickBest 's answer:jex.im/regulex/…
  • Mahdi Pedram
    Mahdi Pedram about 5 years
    Your solution should not allow '012.012.012.012'
  • LHCHIN
    LHCHIN about 5 years
    According to your solution, '00.00.00.00' or '000.000.000.000' are allowed, but I don't think they should be.
  • Harlin
    Harlin about 5 years
    I like this one. This one is the best though maybe technically it doesn't answer the question exactly. Easy to use and easy to read. Many thanks!
  • Rob
    Rob almost 5 years
    I find this regex will cover ips and subnets. and make sure it will not allow leading 0 in each block. /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[‌​0-4][0-9]|1[0-9][0-9‌​]|[1-9]?[0-9])\.(25[‌​0-5]|2[0-4][0-9]|1[0‌​-9][0-9]|[1-9]?[0-9]‌​)\.(25[0-5]|2[0-4][0‌​-9]|1[0-9][0-9]|[1-9‌​]?[0-9])(\/([1-2][0-‌​9]|3[0-2]|[0-9]))?$/
  • elshev
    elshev over 4 years
    @mikemaccana, in a browser
  • mikemaccana
    mikemaccana over 4 years
    @elshev npm has been used the most common source of packages for web browsers for years. Back in 2012 with gulp+browserify, then webpack in 2015 and now with rollup.
  • unixeo
    unixeo over 4 years
    A more precise REGEX is: ^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0‌​-4][0-9]|1[0-9][0-9]‌​|[1-9]?[0-9])\.(25[0‌​-5]|2[0-4][0-9]|1[0-‌​9][0-9]|[1-9]?[0-9])‌​\.(25[0-5]|2[0-4][0-‌​9]|1[0-9][0-9]|[1-9]‌​?[0-9])$ regular-expressions.info/ip.html
  • Rotem
    Rotem about 4 years
    I've upvoted, but please next time add a link to the repository
  • mikemaccana
    mikemaccana about 4 years
    @rotem I've added a link as requested.
  • mikemaccana
    mikemaccana about 4 years
    Not all IP addresses have 4 octets.
  • Ali Zedan
    Ali Zedan over 3 years
    Your solution allowed 123.045.067.089 for example. Leading zeros are not valid ("123.045.067.089"should return false).
  • Ali Zedan
    Ali Zedan over 3 years
    Leading zeros are not valid ("123.045.067.089" should return false), and your solution allowed leading zero, and that it is not correct.
  • avi software
    avi software about 3 years
    Nice solution, but what about "000" blocks? are they valid ip blocks? (exemple: 000.000.000.000)
  • user2956477
    user2956477 about 3 years
    '0.10.10.10' also accepted by this solution
  • abhijithvijayan
    abhijithvijayan almost 3 years
    Extracted the REGEX used in isIP() stackoverflow.com/a/68104187/9387542
  • undefined
    undefined over 2 years
    @DanK.K. 0.0.0.0 is indeed valid en.wikipedia.org/wiki/0.0.0.0
  • Kairat
    Kairat over 2 years
    This does not work for ip: 1.1.1.10
  • Andrei
    Andrei over 2 years
    this solution does not work for IPV6
  • ErickBest
    ErickBest over 2 years
    You can combine this solution with others for a perfect outcome
  • ErickBest
    ErickBest over 2 years
    @AliZedan Solution based on OP question
  • ErickBest
    ErickBest over 2 years
    @Andrei Solution based on OP question.
  • Behzad Shirani
    Behzad Shirani about 2 years
    I want to use it in a jquery website that is npm is not available
  • mikemaccana
    mikemaccana about 2 years
    @BehzadShirani npm is available in JS code for websites. Look up webpack, rollup or similar.