I want the input field to only populate with letters. If you try type in a number, or a special character, nothing is input into the field.
I want this to be validated AS I am typing, NOT validated on submit.
My current code works for the console.log, only logging letter presses.
But the input field still populates.
My current code:
export default function GuessApp() {
function alphaOnly(e) {
if (/[a-zA-Z]/i.test(e.key)) {
console.log(e.key)
return e.key
}
}
return (
<>
<form className="border">
<input className="border border-black w-8 h-8 text-center uppercase" type="text" maxLength="1" onKeyDown={alphaOnly}></input>
</form>
</>
)
}
I keep seeing a "solution" of onkeydown="return /[a-z]/i.test(event.key)"
However, I just get an error that onKeyDown requires a function, string given.
2
Answers
The input field still populates because you’re not using state to control the input value.
Here’s an updated version of your code with controlled state:
You should make it a controlled input.
Use
value={}
and anuseState
to control it.Then only update the state if the value matches your condition.
Dont’ forget an
!e.target.value
so you’re able to clear the input field.