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”
Once you enter a valid IP, you can submit the form
Tweet
9 comments:
i'll have try it
and validate my IP...hohohoho
hohoho...!! nice idea... orite.
great thanks!
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);
});
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.
posee errores varios....... grcias de igual forma ya pude adaptarlo
How would you work this to validate multiple ip address fields on the same page?
Hi
good work but I agree with Ghal; I used "," as separator and the program accepted it. No problem however.
If i wants to test for either Valid URL or Valid IP then what should i have to do?
Post a Comment