Reputation: 16691
I'm trying to write a function that validates an IPv4 address.
Everything appears ok but it doesn't appear to pick up the correct class.
My code is here: http://jsfiddle.net/felix001/X7EuJ/23/
<label for="input">IP</label>
<input type="text" name="input" id="input" size="22" />
<input type="submit" value="submit" "whatmask_input" id="submit" align="right" />
JavaScript:
function ipv4addr(x) {
var REGEX = /^(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 ($x != $REGEX) {
$("#input").addClass(".bad");
}
else {
$("#input").addClass(".good");
}
}
$(document).ready(function() {
$("#submit").click(ipv4addr("#input"));
});
Could anyone tell me the best way to troubleshoot this issue?
Thanks,
Upvotes: 1
Views: 865
Reputation: 37761
Load your browser's development tools console (eg, in Chrome) while you have the fiddler page open.
The first error is:
ReferenceError: Can't find variable: $x
There is no need to prefix variable names with a $, $foo
and foo
are two different variable names. If you have var foo
, then foo
is the variable name.
And looking at the code, this probably doesn't do what you expect:
$("#submit").click(ipv4addr("#input"));
That would be the same as:
var result = ipv4addr("#input");
$("#submit").click(result);
That is, pass the return value of calling ipv4addr
(which is always undefined) into the click method. You probably want to pass a function to get called on every click instead.
Upvotes: 2
Reputation: 38608
Try this function:
function isDottedIPv4(s)
{
var match = s.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
return match != null &&
match[1] <= 255 && match[2] <= 255 &&
match[3] <= 255 && match[4] <= 255;
}
isDottedIPv4("127.0.0.001") // true
isDottedIPv4("448.90210.0.65535") // false
isDottedIPv4("microsoft.com") // false
Upvotes: 1