HTML5 digital input accepts only integer implementation code

Time:2021-10-19

I have seen many articles and posts about this in the past two years, which is really a very convenient thing. However, too many implementations still have loopholes, incomplete implementations, and so on.

The overall concept is reasonable: use HTML 5 attributes to limit the content that can be sent to the server, and then enhance it with JavaScript to limit the content that users can enter in the first place.

So let’s look at these problems and better implement it.

Question 1, bad script

The most common defect is the lack of proper degradation function. It’s good if you want to build a complete stack application in “electron” or “NW. JS”, but this form of thing usually has no place in public facing websites.

As I often say, high-quality scripts should enhance the page that is already working, not the only way for users to use it.

terms of settlement?

Use the pattern and step attributes to restrict valid content.

Problem 2, the regular expression pattern is incorrect or incomplete

The most commonly used pattern is [- / D] *. Its problem is to allow minus signs anywhere. Although you can certainly use type = “number” to solve the problem, it is not a good choice. This is especially true when intercepting keys, because the minus sign can only be the first character.

It can also cause problems because some implementations are “not” regular expressions, which can lead to false positives.

terms of settlement?

For HTML, using a better expression: ^ [- D] \ d * $is more robust and accurate. The minus sign can be the first character at the beginning of the match, followed by zero or more decimals until the end of the string.

For JavaScript, use only regular expressions to test numbers and apply some more practical logic to detect other values.

Easy!

Question 3, using event attributes in Tags

I know there are a lot of mouth breathing people in JSX garbage encouraging this, but if you’re writing about vanilla or other systems, please take your head out of your rectum in 1997 out of love for Christmas.

Putting “onkeypress” or “onchange” in the tag means missing a cache opportunity and violating the principle of separation of concerns. Putting JavaScript into tags in this way is as stupid as everything that has been discarded in HTML 4 strict. Just like if you want to pee on your HTML with attributes like “text white box shadow col-4-s”, please admit your failure, and then go back to writing HTML 3.2 and use all those font / center tags, color, bgcolor, size, border and align attributes, as well as “tables for layout” “To write, you all seem to miss it clearly and cherish it.

This also means that you do not have full / appropriate event handler access.

terms of settlement?

Element.addeventlistener, please use it!

Question 4, each input must be hard coded

Whether I put event attributes into tags through question 3 or capture them by manually obtaining unique IDs, I have hardly found a code base that can actually use plug and play tag applications!

terms of settlement?

Document. Queryselectorall (‘input [type = “number”] [Step = “1”] ‘) gives us all the integer inputs we want, so we can enhance it.

Question 5, some scripts prevent the use of navigation control and normal editing!

By blocking and allowing only minus signs and 0… 9, they can prevent backspace, enter, tab, arrow, delete, insert, and so on. Not all browsers will send these as event.key, depending on what event you hook. For example, some “keypress” events will be filtered out in Firefox and chrome to avoid damaging normal form use, but “old edge” and safari will not, and “Keydown” will not filter anything.

terms of settlement?

Because the “keypress” event is inconsistent across browsers, Keydown is used instead. Then we can use all control keys to return multiple characters in the event.key value. We just need to check that event. Key. Length > 1 to say “continue to allow these”.

As mentioned earlier, all we need is a simple input. Without using JavaScript, it first has as many functions as possible!

HTML:


<input type="number" step="1" pattern="^[-/d]/d*$" />

Accept only integers. If you want to accept only positive numbers, you can change it to pattern = “/ D +”

JavaScript:

Then we can use JavaScript to restrict the user’s input, so that people are not even allowed to enter invalid values.


(function() {
  var integers = document.querySelectorAll(
      'input[type="number"][step="1"]'
    ),
    intRx = /\d/;

  for (var input of integers) {
    input.addEventListener("keydown", integerChange, false);
  }

  function integerChange(event) {
    if (
      event.key.length > 1 ||
      (event.key === "-" &&
        event.currentTarget.value.length === 0) ||
      intRx.test(event.key)
    )
      return;
    event.preventDefault();
  }
})();

We first packaged it in Iife to isolate the scope. Then, grab all the inputs we want to hook on the page and create our regular expression.

I create a regular expression at the beginning of the event instead of inside the event, so we don’t waste time creating it on every damn key. This is where anonymous functions may bring overhead, and where you need to tell “functional programmers” and their “side effects” nonsense.

Loop through all inputs and assign them event handlers.

The above handler just checks our return. Control keys such as arrow, backspace and enter will return complete text to describe them, so if the length of event.key is > 1, we won’t stop them.

If it is a minus sign and the first character, allow it through return.

If it is a number, allow it through return.

If none, block the event.

Live Demo

This is a codebook. It includes several text fields and multiple integer and non integer numeric fields, so you can see that it really hooks only the fields we want.

https://codepen.io/jason-knight/pen/QWGyrwq

Outstanding issues

One thing I might consider adding is to hook the “change” event to intercept pasting, but since the “pattern” attribute does not allow invalid values to be submitted, there should be no problem.

conclusion

Think more about what the user may enter wrong and how to deal with it, but also remember all the other things the user may enter, which have nothing to do with the value itself.

Please always note that many users will actively prevent scripting or make scripts unavailable in UA for security or accessibility reasons. Enhance rather than replace your basic functions!

The plan is to apply these things to all these fields instead of using only a single element from the beginning.

Pay attention to inefficiencies, such as how to generate anonymous functions used as callbacks multiple times… Or how to put scripts into tags will miss cache opportunities across pages or revisited.

After doing these things, implementing such a simple function won’t bother you or annoy users again.

This is the end of this article about the implementation code of HTML5 digital input only accepting integers. For more information about HTML5 digital input integers, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!