Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input type number with plus, minus or "e" inside shows empty value, why?

I've set input type to "number" and now I want to apply some validations to it. I want to prevent starting the function (after clicking the button) if the input contains "+", "-" or "e".

const countBtn = document.getElementById("forge-points-btn");

function quantityHandler() {
    let userInput = document.querySelector(".forge-points-input").value;
    if(userInput.split("").includes("e") || userInput.split("").includes("-")) {
        return;
    }
    // else code
    }
    <input type="number" class="forge-points-input" id="forge-points-input"></input>
    <button type="button" id="forge-points-btn">Count</button>

But to my surprise, it doesn't work because when minus, plus or "e" are entered, e.g. "321-51", "+e-", etc. then userInput equals to empty string. However, when "-55" is entered, then userInput displays correct value. Why is that happening? I'm trying to figure out why can't this solution work. I've seen other solutions on this forum, yet I'd like to understand why this one can't work.

like image 531
Abgar Avatar asked May 19 '26 06:05

Abgar


1 Answers

The MDN Documentation states:

<input type="number"> elements automatically invalidate any entry that isn't a number (or empty, unless required is specified).

You can see this for yourself: providing a value that is not a number automatically invalidates the field.

<p>Equations are not numbers.</p>
<input type="text" id="text-input" value="123-456">
<input type="number" id="number-input" value="123-456">

<p>Signed numbers are numbers.</p>
<input type="number" id="number-input" value="-123">
<input type="number" id="number-input" value="+123">

<p>Exponents are numbers.</p>
<input type="number" id="exponent-input" value="10e5">

If you want to disallow +, -, and e in your input[type=number] then your approach is correct. You must also check that the input is valid, however.

if (!userInput?.length || userInput.includes("e") || ...)

(Side note, you don't need to .split("") since JavaScript can coerce a number into a string.)

like image 86
D M Avatar answered May 20 '26 18:05

D M