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.
The MDN Documentation states:
<input type="number">elements automatically invalidate any entry that isn't a number (or empty, unlessrequiredis 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With