Don't let user to input wrong data - Improving IP address validation JavaScript

285 Views Asked by At

I am trying to make a masked input field to input IP addresses. Almost every solution I found have flaws.

Here https://stackoverflow.com/a/55837333 is the best solution I found, but it is still lets me to enter values higher than 255. Basically it works, but when I am trying to change the entered address, I can set even 192.999.1.1

How to reproduce the error:

  1. Enter an IP address, e.g. 192.168.1.1

  2. Select some part, like 192.__168__.1.1

  3. Start entering numbers, and you get 192.999.1.1

How to improve the code to beat this issue?

here is the code I use

// Credits to @t_m27    
var options = {
  onKeyPress: function(text, event, currentField, options) {
    if (text) {
      var ipArray = text.split(".");
      var lastValue = ipArray[ipArray.length - 1];
      if (lastValue != "" && parseInt(lastValue) > 255) {
        ipArray[ipArray.length - 1] = '255';
        var resultingValue = ipArray.join(".");
        currentField.text(resultingValue).val(resultingValue);
      }
    }
  },
  translation: {
    'Z': {
      pattern: /[0-9]/,
      optional: true
    }
  }
};

$(".ipaddr").mask("0ZZ.0ZZ.0ZZ.0ZZ", options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<input type="text" class="ipaddr" />

2

There are 2 best solutions below

5
mplungjan On BEST ANSWER

Something like this?

// Credits to @t_m27    
var options = {
  onKeyPress: function(text, event, currentField, options) {
    if (text) {
      var ipArray = text.split(".");
      ipArray = ipArray.map(num => num > 255 ? 255 : num)
      var resultingValue = ipArray.join(".");
      currentField.text(resultingValue).val(resultingValue);
    }
  },
  translation: {
    'Z': {
      pattern: /[0-9]/,
      optional: true
    }
  }
};

$(".ipaddr").mask("0ZZ.0ZZ.0ZZ.0ZZ", options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
<input type="text" class="ipaddr" />

0
Felipe N Moura On

In case you want to use a function that returns true if it is a valid ip, or false otherwise, you can use it like this:

function isValidIp(ip) {
  return !ip.split('.').find(part => part > 255);
}

You can use this to show a message or perhaps mark the input as invalid.