My goal is to ensure that a classic <input type="number">
can only show a single minus sign at the beginning of the number (like... normal negative numbers?).
It feels quite dumb to ask this, but currently, in the following input I am able to input "--1", "-1-" or "1--", and in those cases, the value property of the native element just gives me an empty string. Is this somehow intended?
try this :D!
<input
type="number"
onKeyPress={event => {
if (event?.key === "e" || event?.key === "+") {
event.preventDefault();
}
if (event.target.value.length == 0 && event?.key === "-") {
event.target.value = "";
}
if (event.target.value.length > 0 && event?.key === "-") {
event.preventDefault();
}
}}
onPaste={e => {
const reg = "^[-]?[0-9]*\\.?[0-9]*$";
const current = e.target.value;
if (!current) {
e.target.value = "";
}
if (
!(current + e.clipboardData.getData("Text")).match(reg) &&
e.clipboardData.getData("Text").match(reg)
) {
e.target.value = "";
}
if (!e.clipboardData.getData("Text").match(reg)) {
e.preventDefault();
}
}}
/>
The key press events allow for single minuses and avoid double minuses
Furthermore onPaste method will allow only valid numbers to be pasted
If the to be pasted clipboard is not a number then it will not be pasted.
If the current value + the clipboard is not a number only the clipboard will be pasted otherwise the current value + the to be pasted clipboard will be pasted.
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