How To Validate Ip Address On Multiple Inputs?
I am trying to check if what I submit via an input type='text' is a valid IP Address. I have found this example online for JS IP Validation but it is only for one input and I have
Solution 1:
You would want to wrap the algorithm in a reusable function instead
functionValidateIPaddressOnChange(input, type)
{
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]?)$/;
var strtype = "";
switch(type){
case"ipaddress": strtype = "IP Address"; break;
case"gateway": strtype = "gateway"; break;
case"dns": strtype = "DNS"; break;
case"subnet": strtype = "subnet mask"; break;
}
if(!input.value.match(ipformat)) {
input.focus();
alert("You have entered an invalid " + strtype + " format!");
}
}
In your HTML, attach an onchange event on the input element, which will then execute an individual validation whenever the user finishes changing the inputs
<inputtype="text" name="networkName" value="" pattern=".{5,30}" title="Enter between 5 and 30 characters" onchange="ValidateIPaddressOnChange(this, 'ipaddress')" />
You can keep your old validation function, that one actually validates everything on submission, which is also fine and dandy. There are obviously better ways to do this, but for now, this can do without diverging much from what you already started.
Solution 2:
You can use the match()
to match your regex to the input and check if it's correct format
Example of valid IP address
115.42.150.37
192.168.0.1
110.234.52.124
var pattern = /^(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]?)$/;
functioncheck() {
$.each($(".ip"), function() {
if (!$(this).val().match(pattern)) {
$(this).addClass("wrong");
$(this).removeClass("correct");
} else {
$(this).addClass('correct');
$(this).removeClass("wrong");
}
});
}
.wrong {
color: red;
}
.correct {
color: green;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><inputclass="ip" /><br><inputclass="ip" /><br><inputclass="ip" /><br><inputclass="ip" /><br><buttononClick="check()">Check ip address</button>
Post a Comment for "How To Validate Ip Address On Multiple Inputs?"