DelphiFAQ Home Search:

A regular expression for IP numbers and ranges

 

comments2 comments. Current rating: 5 stars (1 votes). Leave comments and/ or rate it.

Question:

I need a regular expression for IP ranges such as:
192.168.0.0/16
123.45.67.89

I want to use it in JavaScript to validate user input. Do you have some code?

Answer:

Yes, use the code shown below.

var IP_Validator_Regexp='(1\d{0,2}|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|' + 
'[3-9]\d?|0)\.(1\d{0,2}|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|[3-9]\d?|0)' +
'\.(1\d{0,2}|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|[3-9]\d?|0)\.(1\d{0,2}' + 
'|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|[3-9]\d?|0)(\/(?:[012]\d?|3[012]?' +
')){0,1}$';

  // how to use it in Javascript

  var regex =/IP_Validator_Regexp/;
  if (!(regex.test(document.getElementById('user_ip').value))) {
    alert('This is not a valid IP number');
    return;
  }

Content-type: text/html

Comments:

2009-10-21, 12:20:03
anonymous from United States  
this will accept 127.0.0 as valid ip
2010-03-07, 02:45:55
anonymous  
rating
This is a wonderful regexp, thanks!
No problem with 127.0.0.

However, the CIDR notation is wrong.
It accepts /0 through /3 and /10 through /32 (of course it should accept all of /0 through /32).

I believe the fixed regexp is:

var IP_Validator_Regexp='(1\d{0,2}|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|' +
'[3-9]\d?|0)\.(1\d{0,2}|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|[3-9]\d?|0)' +
'\.(1\d{0,2}|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|[3-9]\d?|0)\.(1\d{0,2}' +
'|2(?:[0-4]\d{0,1}|[6789]|5[0-5]?)?|[3-9]\d?|0)(\/(?:[012]\d?|3[012]?|[456789]' +
')){0,1}$';

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: