0

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>
bleah1
  • 471
  • 3
  • 18
  • 1
    [The HTML5 placeholder attribute is not a substitute for the label element](http://www.456bereastreet.com/archive/201204/the_html5_placeholder_attribute_is_not_a_substitute_for_the_label_element/) – Quentin Jul 08 '19 at 10:04
  • What does this have to do with everything ? – bleah1 Jul 08 '19 at 10:06
  • It's a recommendation on how you can improve your code (which isn't an answer to the question, so it is a comment and not an answer). – Quentin Jul 08 '19 at 10:07
  • Ooooh. I had no idea `label` even existed. Thanks ! – bleah1 Jul 08 '19 at 10:10

2 Answers2

1

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.

Abana Clara
  • 4,602
  • 3
  • 18
  • 31
  • So this method alerts the user if the input is wrong the moment they change to another input, but it doesn't stop them from submitting the form with wrong values. – bleah1 Jul 08 '19 at 11:20
  • Also `var type = "";` isn't needed because you pass `type` to the function and by using it you are actually replacing what ever comes through the function's `type` argument with `""`. – bleah1 Jul 08 '19 at 11:21
  • @bleah1 1) You specifically asked to validate each input individually. I know it doesn't stop users from submitting the form with wrong values which is why I pointed out you can keep your old code. 2) I definitely forgot to use another variable. – Abana Clara Jul 08 '19 at 13:24
  • I figured it out eventually. – bleah1 Jul 08 '19 at 15:23
0

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>
PEPEGA
  • 2,214
  • 20
  • 37
  • Can I use `` instead of `` ? – bleah1 Jul 08 '19 at 10:31
  • @bleah1 Yes as long as the submit dosnt refresh the page you can use the code above. Sorry my answear was with jquery, but basically all you need is the match() that returns either true or false. – PEPEGA Jul 08 '19 at 10:35
  • I am a noob when it comes to everything related to JS so I don't really care what framework it is as long as I understand how the script works. Also, do you think I can change the color of another element instead of the input. Right now, by using `this` the color change is done to the appropriate input element. But let's say I have a label tag next to the input: `` How can I change the label's color but keep the code clean as well. – bleah1 Jul 08 '19 at 10:39
  • The `submit` does usually refresh the page but this time it won't refresh or submit until all the input fields are filled up, because they are all `required`. And even if I fill them up, the `submit` won't refresh or submit until the inputs go through the validation. I think. – bleah1 Jul 08 '19 at 10:44
  • Sooo... I can't make this work... I am using this `` and it works with my other scripts. I also replaced the submit with an actual button like in your example. I have also deleted `action=""` from the `form` element to test if it works and it doesn't. – bleah1 Jul 08 '19 at 11:02