Validate IP Address using jQuery

I had recently posted on Add a Custom Validation Method to the jQuery Validation Plugin. A user asked me over twitter asking how to validate IP address using this method.

Here’s the same custom validation method that now validates an IP address. I am using regex to do so (The regular expression was searched on the net)

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Validate IP Address using jQuery</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript" src=
"http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$.validator.addMethod('IP4Checker', function(value) {
var ip = "^(?:(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)\.){3}" +
"(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)$";
return value.match(ip);
}, 'Invalid IP address');

$('#form1').validate({
rules: {
ip: {
required: true,
IP4Checker: true
}
}
});

});
</script>
</
head>
<
body>
<
form id="form1">
<
input id="ip" name="ip" type="text" />
<
input id="Submit1" type="submit" value="submit" />
</
form>
</
body>
</
html>

On running the code, enter an IP address. The validation detects an invalid IP and displays the message “Invalid IP address”

Validate IP jQuery

Once you enter a valid IP, you can submit the form

Validate IP jQuery

Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

9 comments:

Beben Koben said...

i'll have try it
and validate my IP...hohohoho

gumuruhsspj said...

hohoho...!! nice idea... orite.

great thanks!

morfey said...

Wrong regexp!

True is:
$.validator.addMethod('IP4Checker', function(value) {
var ip = /^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}$/;
return value.match(ip);
});

Ghal Maraz said...
This comment has been removed by the author.
Ghal Maraz said...

Hi,

I tried your example and i think a found a little mistake.

You should user "\\." to escape the dot, because the '\' itselfs needs to be escaped. If you don't it means any character can be a seperator for the ip quartet.

Ray R said...

posee errores varios....... grcias de igual forma ya pude adaptarlo

Anonymous said...

How would you work this to validate multiple ip address fields on the same page?

Unknown said...

Hi
good work but I agree with Ghal; I used "," as separator and the program accepted it. No problem however.

Unknown said...

If i wants to test for either Valid URL or Valid IP then what should i have to do?