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

9 comments:

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

    ReplyDelete
  2. hohoho...!! nice idea... orite.

    great thanks!

    ReplyDelete
  3. 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);
    });

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. 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.

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

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

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

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

    ReplyDelete