Hello all,
I have two regular expressions. one for Ip address and another one for port.
for IP Address –
var regexp = new RegExp(“/\.[0-255]\.[0-255]\.[0-255]$/”);
For port
var regexp2 = new RegExp(“/+$/”);
But none of these matches desired output. I mean regexp doesn’t match 190.23.67.90 and regexp2 doesn’t match for 8090.
Can anybody tell me the mistake I am making?
Thanks a lot for your time
Did you do it with a regex?
I wrote an IP regex once and it was ridiculously long. I just wrote a function that did some basic string parsing which was not only better, but faster.
actualy I converted it to
var regexp = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
and then I checked $1, $2, $3 and $4 for the range 0-255
var regexp = /^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/;
That way you would only have to check if the number is above 255.
[0-255] is the same as [0125]
\d is the same as [0-9]
The complete regexp to check for an IPv4 address is this.
var regexp = /^(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])$/;
Any chance you could post that function?
Don’t have it offhand, but it’s very similar (if not identical) to this
function verifyIP( $ip )
{
list( $ip, $port ) = explode( ":", $ip );
if ( $port != null && !ctype_digit( $port ) )
{
return false;
}
$octets = explode( '.', $ip );
if ( count( $octets ) == 4 )
{
foreach ( $octets as $octet )
{
if ( !ctype_digit( $octet ) || $octet > 255 || '' == $octet )
{
return false;
}
}
return true;
}
return false;
}
Thanks, beetle.
It’s not really that complicated now that I’ve had a look at it.
Note: That function is in PHP, so it won’t work as JavaScript without several modifications.
Haha, ya, sorry. Been writing so much PHP lately I forgot I was in the JS forum
But you are right, changing it over would be pretty easy.