Pawan Pawan - 2 months ago 5x
jQuery Question

Try to validate IP Address with javascript

I'm a beginner to JQuery. Now, I'm trying to make a form to post back to server. There are some "input" that contains ip address which should be validate before submitting. Now I have done a javascript function which work well. But now I'm trying to add this function into jquery selection. Just confuse how to do it.

This is my validate javascript code.

function ValidateIPaddress(Ipfield)
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]?)$/;

return true;
return false;


and this is now how I implement for this validation.

<input type= "text" name= "LocalIP" style= "margin-right:10px " value="" class="ip" onfocusout="ValidateIPaddress(document.getElementById('LocalIp'))" id="LocalIp" > Remote VIP Address :
<input type= "text" name= "RemoteVIPAddr" style= "margin-right:10px" value="" class="ip" onfocusout="ValidateIPaddress(document.getElementById('RemoteIp'))" id="RemoteIp" >
Remote VIP Port :
<input type= "text" name= "RemoteVIPPort" style= "margin-right:10px" value="5004" class="ip" onfocusout="ValidatePort(document.getElementById('RemoteVIPPort'))" id="RemoteVIPPort">

Now I want to use jquery selection to always check if there are some invalid input. Which is something like this but with my own design function.

$("input.ip:visible").filter(function() { return this.ValidateIPaddress === true }).addClass("invalid");

Anyone has idea bout it?


You're not calling ValidateIPAddress in your filter function, you're just testing whether the DOM element has a non-empty property named ValidateIPAddress. It should be:

$("input.ip:visible").filter(function() {
    return ValidateIPAddress(this);