4

So I want to have an input of type number <input type="number"> and I want to RESTRICT users from ENTERING DECIMAL VALUE

Note: I'm hiding the spin buttons of the input type text. Know more here

EDIT: ANYTHING WILL WORK! EVEN JAVASCRIPT!


I searched a lot but found nothing.

I did find this answer but it basically blocks the use of any other key on the keypad except the number keys, so the basic problems occur such as the user cannot use backspace and cut the number entered, another problem is the user cannot use tab to change focus onto the next input.


Thank You!

Adarsh Dubey
  • 302
  • 2
  • 12
  • "_I want to RESTRICT users from ENTERING DECIMAL VALUE_" plus this "_and NOT JavaScript_" - You cannot achieve this goal without JavaScript. – Randy Casburn Nov 21 '21 at 14:02
  • You can use the [`pattern`](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern) attribute, but it may not do what you want without JavaScript – evolutionxbox Nov 21 '21 at 14:03
  • @RandyCasburn it is not preferred, but like I said, anything will work fine – Adarsh Dubey Nov 21 '21 at 14:05
  • 1
    @evolutionxbox - pattern attribute does not control what is typed by the end user - only applies to constraint API and what is accepted as a _valid_ input. You can also use the `step` attribute, but also doesn't _restrict_ input. – Randy Casburn Nov 21 '21 at 14:07
  • @RandyCasburn indeed, it is not an exact solution. Hence the comment not an answer. – evolutionxbox Nov 21 '21 at 14:08
  • You can use the step attribute - if it is 1 then decimals are not allowed and the system will complain (with an explanation) when the user tries to submit. – A Haworth Nov 21 '21 at 14:10
  • on `keyup` check the value, adjust it if necessary – ProDec Nov 21 '21 at 14:22
  • @AHaworth no, I tried it but it doesn't really work – Adarsh Dubey Nov 21 '21 at 14:44
  • This cant be achieved with just HTML or CSS, you may have to do some JS and regEx magic. – Salus Sage Nov 21 '21 at 14:48
  • @SalusSage yes, tell me, now I'm starving for an answer – Adarsh Dubey Nov 21 '21 at 15:13
  • I like this one personally https://stackoverflow.com/a/62351420/2622839 This post as more options, see if you like any. – Salus Sage Nov 21 '21 at 15:46
  • Could you say what doesn't work about using step - is it because it doesn't check until the submit? If you want checking as the user types you may have to use JS. – A Haworth Nov 21 '21 at 16:05
  • @AHaworthyeah...I'm never actually submitting then form, it's for a real-time web application and I use the even listener of `input`. Please tell me a way to do it in JavaScript. – Adarsh Dubey Nov 22 '21 at 13:40
  • So do validation and show an error to the user when they enter in a decimal number. – epascarello Nov 23 '21 at 13:13

2 Answers2

4

Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...

document.querySelector('input').addEventListener('input', e => {
  e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>

But you really should not do it! For at least the following reasons:

  1. Forbidding user input is, by and large, perceived as disrespectful and drives users away. In short, it reduces any user engagement metric you can think of (funneling, sales, visits, sharing, etc...). Don't take my word for it. Do some A/B testing: present the same form with and without blocking user input and look at the results.
  2. Form elements are just tools to help users give you data. But they are completely by-pass-able. If you give me a form I can send whatever I want using it, by simply opening the browser console. The validation must be done on server side. If you're using the value to do something on client side, sanitize the input value in the method, without changing user input.
  3. A respectful way to inform users decimal values are not valid is by making the input :invalid, using the pattern attribute ( e.g: pattern="[0-9]"), styling accordingly (e.g: :invalid { border-color: red }), and displaying an appropriate message.
    Don't delete or block user input. They'll do it themselves if you tell them why the value is invalid.
  4. When following web standards, your solution lasts. When you come up with hacks, there will always be the odd device in which your hack doesn't work. You don't know where things will be in 1-2 years from now, nevermind 5 or 10.
  5. Last, but not least, have a closer look at Constraint Validation. You'll need to know and use it when creating quality UX and accessible forms.
tao
  • 82,996
  • 16
  • 114
  • 150
1

This is one option for creating an input element using javascript to limit the values that can be entered. I create an array of allowed keys, including all the digits, backspace, and tab as you specified. I added an event listener for the keydown event, and if the key pressed is not in the allowed group, I prevent the default action, or prevent the value from being entered.

I also added an event listener to the paste event, as you could right click paste and enter information that does not meet the criteria. Instead of trying to validate pasted values I disable pasting all together.

If you have any questions, please ask.

const allowedKeys = [..."0123456789", "Backspace", "Tab"];
const myInput = document.querySelector("input");
myInput.addEventListener("keydown", e => {
  const key = e.key;
  const allowed = allowedKeys.includes(key);
  if (!allowed) e.preventDefault();
});
myInput.addEventListener("paste", e => e.preventDefault());
<input type="number">
async await
  • 1,967
  • 1
  • 8
  • 19