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.
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.)
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
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