skip to Main Content

I’m kinda at my wits end with this as it is not behaving like other examples I’ve tried online.

I have some input validation for numbers:

$('body').on("input", 'input[type="number"]', function(){
        const regex = /[^0-9]/g;
        const val = $(this).val();
        console.log(val.replace(regex, ''));

Any time I enter a character that isn’t a digit it returns an <empty string> in the console.

I’ve tried this same code in a few sandboxes and it works perfectly, returning numbers.

2

Answers


  1. The way HTML5 "number" inputs are specified, you’re supposed to get nothing (well, the empty string) as the value when it doesn’t contain a proper number.

    HTML5 validation stuff in general to me seems like it was expressly defined to work without any "oversight" by JavaScript. I’m sure that’s an oversimplification of an extremely complicated specification process over years, but it’s still true that that’s the "rule of thumb" in my head for what to expect.

    Login or Signup to reply.
  2. When you get the value of a type="number" input, it returns an empty string if the user input is not a valid number. From the HTML spec

    The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search