javascriptjquerymaskedinput

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


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" />


Solution

  • 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" />