Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict user input character length of HTML5 input type="number"?

How do I restrict user input to a given length in an HTML5 input[type=number] textbox?

the answers to

How can I limit possible inputs in a HTML5 "number" element?

do not handle illegal inputs

<input class="quantity" type="number" min="0" max="99999" maxlength="5" />

$("quantity").keyup(function(){
    var $field = $(this);
    if ($field.val().length > Number($field.attr("maxlength"))) {
        var value = $field.val().slice(0, 5);
        $field.val(value);
    }
});

I know the maxlength attribute is not supported, but I use it to obtain the given length.

The above code works fine in firefox, but in chrome and safari it works only if I input five "VALID" characters. When I start typing any invalid characters, e.g. "a", "b" etc., I am able to type in more letters and the textbox color changes to red.

I found that when the input becomes invalid the $field.val() returns always empty string and the $field.val().length returns 0.

I even tried converting the keyCode to character intended to input and store it in a "data-value" attribute to the input box to check against and overwrite the value of the input but it didn't seem to be reliable.

Is there any solution with which I can make the input[type=number] behave same as input[type=text][maxlength=5]?

like image 711
Gopu Avatar asked Aug 07 '13 13:08

Gopu


1 Answers

Here is my suggestion after testing a few things

  1. it handles more than one field with the quantity class
  2. it handles illegal input where supported
  3. initialises by storing all defaultValues of the fields with the class
  4. handles a weirdness with .index()
  5. works in IE<10 too
  6. tested in Safari 5.1 on Windows - it reacted to the is(":invalid") which however is invalid in IE8

Live Demo

var inputQuantity = [];
$(function() {
  $(".quantity").each(function(i) {
    inputQuantity[i]=this.defaultValue;
     $(this).data("idx",i); // save this field's index to access later
  });
  $(".quantity").on("keyup", function (e) {
    var $field = $(this),
        val=this.value,
        $thisIndex=parseInt($field.data("idx"),10); // retrieve the index
    // NOTE :invalid pseudo selector is not valid in IE8 so MUST be last
    if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) { 
        this.value = inputQuantity[$thisIndex];
        return;
    } 
    if (val.length > Number($field.attr("maxlength"))) {
      val=val.slice(0, 5);
      $field.val(val);
    }
    inputQuantity[$thisIndex]=val;
  });      
});
like image 111
mplungjan Avatar answered Oct 12 '22 09:10

mplungjan