简体   繁体   中英

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 4.

The inputs:

        <form method="POST" name="simple_form" action="/staticIP" onsubmit="return ValidateIPaddress()">
            <div class ="text_input">
                <input type="text" placeholder="Network Name (SSID)" name="networkName" value="" pattern=".{5,30}" title="Enter between 5 and 30 characters">
            </div>        
            <div class="text_input">            
                <input type="password" placeholder="Password" name="networkPassword" value="" minlength="8" pattern=".{8,63}" title="Enter between 8 and 63 characters">
            </div>
            <div class ="text_input">
                <input type="text" placeholder="IP Address" name="ipAddress" value="" required>
            </div>        
            <div class="text_input">            
                <input type="text" placeholder="Gateway" name="gateway" value="" required>
            </div>
            <div class ="text_input">            
                <input type="text" placeholder="Subnet Mask" name="subnet" value="" required>
            </div>
            <div class ="text_input">            
                <input type="text" placeholder="DNS" name="dns" value="" required>
            </div>                 
            <input class="button" type="submit" name="" value="Save and Reboot">
        </form>

JS:

    <script>
        function ValidateIPaddress() 
        {
            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 ipaddr = document.forms["simple_form"]["ipAddress"];
            var gateway = document.forms["simple_form"]["gateway"];
            var subnet = document.forms["simple_form"]["subnet"];
            var dns = document.forms["simple_form"]["dns"];
            var counter = 0;

            if(ipaddr.value.match(ipformat)) {
                ipaddr.focus();
            } else {
                window.alert("You have entered an invalid IP Address!");
                ipaddr.focus();
                return (false);
            }
            if(gateway.value.match(ipformat)) {
                gateway.focus();
            } else {
                window.alert("You have entered an invalid GATEWAY Address!");
                gateway.focus();
                return (false);
            }            
            if(subnet.value.match(ipformat)) {
                subnet.focus();
            } else {
                window.alert("You have entered an invalid SUBNET Address!");
                subnet.focus();
                return (false);
            }            
            if(dns.value.match(ipformat)) {
                dns.focus();
            } else {
                window.alert("You have entered an invalid DNS Address!");
                dns.focus();
                return (false);
            }
        }
    </script>

As you can see I don't have any return(true) . Do I need it ?

Also, this makes me need to input all of the values before it can actually check them.

Is there any other way of checking them individually ?

I also have found some Regex rules here :

pattern = " (?<!\S)((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b|\.\b){7}(?!\S) "
/* or */
pattern="^([1-9]|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))$"

They seem to work, but I want to try using JS.

Response:

<script type="text/javascript" src="jquery-1.12.4.min.js"></script>

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

            switch(type){
                case "ipaddress": type = "IP Address"; break;
                case "gateway": type = "Gateway"; break;
                case "subnet":  type = "Subnet Mask"; break;
                case "dns": type = "DNS"; break;
            }

            if(!input.value.match(ipformat)) {
                document.getElementById(input.name).className =
                    document.getElementById(input.name).className.replace
                    ( /(?:^|\s)correct(?!\S)/g , '' )
                document.getElementById(input.name).className += " wrong";
                input.focus();
                alert(type + " is invalid!");
                return(false);
            }
            else if(input.value != null){
                document.getElementById(input.name).className =
                    document.getElementById(input.name).className.replace
                    ( /(?:^|\s)wrong(?!\S)/g , '' )                
                document.getElementById(input.name).className += " correct";
            }
        }

        function ValidateIPaddress()
        {
            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 ipaddr = document.forms["simple_form"]["ipAddress"];
            var gateway = document.forms["simple_form"]["gateway"];
            var subnet = document.forms["simple_form"]["subnet"];
            var dns = document.forms["simple_form"]["dns"];
            var counter = 0;

            if(ipaddr.value.match(ipformat)) {
                ipaddr.focus();
            } else {
                alert("You have entered an invalid IP Address!");
                ipaddr.focus();
                return (false);
            }
            if(gateway.value.match(ipformat)) {
                gateway.focus();
            } else {
                window.alert("You have entered an invalid GATEWAY Address!");
                gateway.focus();
                return (false);
            }            
            if(subnet.value.match(ipformat)) {
                subnet.focus();
            } else {
                window.alert("You have entered an invalid SUBNET Address!");
                subnet.focus();
                return (false);
            }            
            if(dns.value.match(ipformat)) {
                dns.focus();
            } else {
                window.alert("You have entered an invalid DNS Address!");
                dns.focus();
                return (false);
            }
        }
    </script>
        <form method="POST" name="simple_form" action="/staticIP" onsubmit="return ValidateIPaddress()">
            <div class ="input_row">
                <input type="text" class="input_text" placeholder="Type here Network Name (SSID)" id="networkName" name="networkName" value="" pattern=".{5,30}" title="Enter between 5 and 30 characters" required />
                <label class="label_" for="networkName">Network Name (SSID)</label>
            </div>        
            <div class="input_row">                
                <input type="password" class="input_text" placeholder="Type here Password" id="networkPassword" name="networkPassword" value="" minlength="8" pattern=".{8,63}" title="Enter between 8 and 63 characters" required />
                <label class="label_" for="networkPassword">Password</label>
            </div>
            <div class ="input_row">                
                <input type="text" class="input_text" placeholder="Type here IP Address" id="ipAddress" name="ipAddress" value="" required
                onchange="ValidateIPaddressOnChange(this, 'ipaddress')" />
                <label class="label_" for="ipAddress">IP Address</label>
            </div>        
            <div class="input_row">              
                <input type="text" class="input_text" placeholder="Type here Gateway" id="gateway" name="gateway" value="" required
                onchange="ValidateIPaddressOnChange(this, 'gateway')" />
                <label class="label_" for="gateway">Gateway</label>
            </div>
            <div class ="input_row">            
                <input type="text" class="input_text" placeholder="Type here Subnet Mask" id="subnet" name="subnet" value="" required
                onchange="ValidateIPaddressOnChange(this, 'subnet')" />
                <label class="label_" for="subnet">Subnet Mask</label>
            </div>
            <div class ="input_row">
                <input type="text" class="input_text" placeholder="Type here DNS" id="dns" name="dns" value="" required
                onchange="ValidateIPaddressOnChange(this, 'dns')" />
                <label class="label_" for="dns">DNS</label>
            </div>                 
            <input class="button" type="submit" name="" value="Save and Reboot">
        </form>

You would want to wrap the algorithm in a reusable function instead

function ValidateIPaddressOnChange(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

<input type="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.

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]?)$/; function check() { $.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; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="ip" /><br> <input class="ip" /><br> <input class="ip" /><br> <input class="ip" /><br> <button onClick="check()">Check ip address</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM