January 5th, 2007

Check IP format with Regular Expressions in JavaScript

Here's a quick JavaScript function to check that a user has entered a valid IP address. Don't ask me why, but there may be times when you need a user to input an IP address, rather than just grab theirs. And it's always easier to check first on the client side with JavaScript than having to do all the validation on the post back to the server with PHP!


var filter = /^([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+\.([1-9][0-9]{0,2})+$/;
	 if (!filter.test(f.ip.value)) {
		alert('Please enter a valid IP');
		f.ip.focus();
		return false
 	 }
Share

4 Responses to ' Check IP format with Regular Expressions in JavaScript '

Subscribe to comments with RSS or TrackBack to ' Check IP format with Regular Expressions in JavaScript '.

  1. jocke said,

    on September 30th, 2008 at 5:48 am

    This does not work. It vill not accept anything with a zero in it, e.g. 213.0.2.12

  2. Chris said,

    on January 21st, 2009 at 7:34 pm

    Hey Man,

    I think this is probably the filter you really want:

    var filter = /^(([1-9][0-9]{0,2})|0)\.(([1-9][0-9]{0,2})|0)\.(([1-9][0-9]{0,2})|0)\.(([1-9][0-9]{0,2})|0)$/;

    It allows the entry to be a single '0' which is valid. And gets rid of those +'s which allow an unlimited number of those number matches to be made.

  3. atar said,

    on February 10th, 2010 at 4:40 am

    Both code does not work.It will accept 999.999.999.999 as ip address

  4. Ceilingfish said,

    on December 9th, 2010 at 10:23 am

    That's because that's not a valid IP address

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word