I want to be able to prevent a user entering characters into a textbox based on what the text of the textbox would be if the character gets entered.
The initial thought is to do something like this:
<input type="text" id="test" />
document.getElementById("test").addEventListener("keypress", (e) => {
// Get the current text
const currentText = e.target.value;
// Get the new char entered by the user
const newChar = String.fromCharCode(e.keyCode);
// The problem is that we don't know where the cursor is,
// i.e. we CANNOT guarantee that the new text will be:
const newText = `${currentText}${newChar}`;
// ...because that assumes the cursor is at the end of the current text
// I want to check that newText is valid before allowing the event to go through
if(!someCustomCheck(newText)) {
e.preventDefault();
}
});
The comments explain my issue, but here's a further example: imagine we have an input that allows numbers with 2 decimal places to be added:
- We have an empty input box
- We type
1
into it; this is valid, so we allow it - We type
.
into it, which again is valid, then2
and3
- This gives us a textbox with
1.23
- The user then types
4
:- The problem is that this
4
could be1.234
, which would be invalid, but it could also be41.23
or14.23
, which is valid
- The problem is that this
I cannot see a way to get the cursor position in the event
in the click event, nor can I see a property in e.target
(like you can in the keyup
event) that gives the final text of the input.
Is there a way to do this?