0

There are numerous similar questions regarding this, but no answers are actually working. I would like to PREVENT (not validate afterwards) users from ENTERING more than 4 digits after the decimal point in an HTML input field. I can easily validate the input once the user navigates away from the field, but my intent is to actually PREVENT altogether the user from inputting more than 4 digits.

I am using the following code upon creating the input field:

 text.setAttribute('step', '.0001')
 text.setAttribute('placeholder', '00.0000')
 text.addEventListener('focusout', () => this.validate(tId))

In my following focusout validate method:

 validate (tId) {
    let val = document.getElementById('text' + tId).value
    let txtInput = document.getElementById('text' + tId)
    // Validation
 }

I have tried the following but without succes:

 if (val.match('^\\d+(\\.\\d{1,4})?$')) {
 }

And

 val = parseFloat(val).toFixed(4)

But these are not working as I wish. They do properly validate the input once navigating away from the field, but do not actually PREVENT the user from entering more than 4 digits.

user229044
  • 232,980
  • 40
  • 330
  • 338
JF0001
  • 819
  • 7
  • 30
  • 2
    Use a `keydown` event listener and execute `event.preventDefault()` if you want the keypress to be ignored – Phil Mar 26 '21 at 00:31
  • 1
    Does this answer your question? [How to prevent keypress two digits after a decimal number?](https://stackoverflow.com/questions/15680506/how-to-prevent-keypress-two-digits-after-a-decimal-number) – dale landry Mar 26 '21 at 00:39
  • Thank you dale landry, but I am not using JQuery. – JF0001 Mar 26 '21 at 01:06
  • Don't? You are perfectly capable of taking whatever people paste into your field and convert it at submission time. If someone types more than 4 letters, but that includes paces and dashes, etc, your form should go "that's fine, I'm going to strip those before actually running the form submission". Don't practice defensive programming on the web. You can easily be better than that. – Mike 'Pomax' Kamermans May 02 '21 at 04:06

0 Answers0