Link to home
Start Free TrialLog in
Avatar of nicolle
nicolle

asked on

IP validation ?

How do I use Javascript to do IP validation ? The IP validation will validate 255.255.255.255 or 0.x.x.x as invalidate IP. Any sample ?
Avatar of jaysolomon
jaysolomon

this?

<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
<!--Begin
function isIPaddy(strValue){
                              // 255  .    255  . 255  . 255  
      var objRegExp = /^\d{3}\.{1}\d{3}\.\d{3}\.\d{3}$/
      return objRegExp.test(strValue);
}
function validateForm(fObj){
      if(!isIPaddy(fObj["ip"].value)){
            alert("Please enter a correct IP address\n\nEx. 255.255.255.255");
            fObj["ip"].select();
            return false;
            }
      return true;
}
             
//End-->
</script>
</head>
<body>
<form name="form1" method="post" action="" onSubmit="return validateForm(this);">
  <input type="text" name="ip">
  <input type="submit" name="btnSubmit" value="Submit">
</form>
</body>
</html>
Avatar of nicolle

ASKER

your code does not accept 1.1.1.1.

Sorry ! I should state clear to you. In my case, 255.255.255.255 and first part begin
with 0 are invalid.
ok so

 var objRegExp = /^[1-9]{1,3}\.{1}\d{1,3}\.\d{1,3}\.\d{1,3}$/

is 255.255.255.255 invalid
Avatar of nicolle

ASKER

Yes, 255.255.255.255 is invalid
ASKER CERTIFIED SOLUTION
Avatar of jaysolomon
jaysolomon

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:))) LOL

if(fObj["ip"].value == "255.255.255.255")

<-- That was funny !

I would double points for that!
Avatar of nicolle

ASKER

makc,

You have better regular expression on that ?
actually, i don't see why to use regexp at all. make four inpus for each byte, use isNaN(input.value) and check it to be in 1...254 range. that's it, isn't it?
isNaN(parseInt(input.value)), maybe, but you got the picture.