Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<input type="number"> does not prevent the invalid numbers inputting, but "element.value" does not allow me to correct them

From the MDN documentation about <input type="number">:

They include built-in validation to reject non-numerical entries.

Does it mean "reject when try to submit the HTML form"? I inputted "4e4--23". HTML has not rejected it.

enter image description here

Therefore, <input type="number"> can not prevent the inputting of non-number value. I don't care about I it if I can programically correct user's input. For example, user inputted the minus sign not in the first position - using JavaScript, theoretically I can remove it.

However here is unobvious JavaScript behavior: when input element has "number" attribute and value is invalid number, Element.value returns an empty string. It's very tricky programmatic validation: because we have empty string value, the validator will return "The input must not be empty. Please input the value." error while input in not empty!

document.getElementById("target").addEventListener("input", blackbox => {
 console.log(document.getElementById("target").value);
});
<input type="number" value="" id="target">

How can I get the actual inputted value? (If you know Vue, please add the solution for Vue, too.)

like image 713
Takeshi Tokugawa YD Avatar asked Sep 09 '25 14:09

Takeshi Tokugawa YD


1 Answers

try this:

I only accept numbers:
<input type="text" v-model="form.availability" oninput="this.value = this.value.replace(/[^0-9]/g, '');">
<br>
I only accept numbers inlcuding a point:
<input type="text" v-model="form.availability" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
<br>
EDIT: I accept negative numbers inlcuding a point:
<input type="text" v-model="form.availability" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1');">
<br>
EDIT: I accept negative numbers inlcuding a point:
<input type="text" v-model="form.availability" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1').replace(/(\..*)\./g, '$1');">
<br>
EDIT2: I accept negative numbers inlcuding a point (only one "minus" sign):
<input type="text" v-model="form.availability" oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1').replace(/(\..*)\./g, '$1').replace(/(\-.*)\-/g, '$1');">
<br>
EDIT3: I also accept "e" and "E"
<input type="text" v-model="form.availability" oninput="this.value = this.value.replace(/[^0-9\.\-\e\E]/g, '').replace(/(\..*)\./g, '$1').replace(/(\..*)\./g, '$1').replace(/(\-.*)\-/g, '$1').replace(/(\e.*)\e/g, '$1').replace(/(\E.*)\E/g, '$1');">
<br>

Different browsers treat the "input type number" differently

like image 67
Fábio Garcia Avatar answered Sep 12 '25 03:09

Fábio Garcia