0

I have to validate the ip address submitted from the form. I have tried the code below in jQuery, but it does not work.

var IpAddresslanText = $("#IpAddresslan").val();
if(IpAddresslanText == '') {
  alert('enter IpAddresslan');
  return false;
}
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;  
if(!IpAddresslanText.match(ipformat)) {  
  alert("You have entered an invalid IP address!");
  return false;
}  

Thanks in advance

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
user3239377
  • 3
  • 2
  • 4

2 Answers2

0

Try this

jQuery.validator.addMethod('validIP', function(value) {
  var split = value.split('.');
  if (split.length != 4) 
    return false;

  for (var i=0; i<split.length; i++) {
    var s = split[i];
    if (s.length==0 || isNaN(s) || s<0 || s>255)
      return false;
  }
  return true;
}, ' Invalid IP Address');

Usage:

jQuery("#myForm").validate({
  rules: {
    name: {
      validIP: true
    }
  }
}
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
0

match return an array.

So try to change your condition like this:

if(IpAddresslanText.match(ipformat)===null)
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73