Search code examples
javascripthtmlreactjs

ReactJS and HTML - How to only allow letters on input?


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.


Solution

  • 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:

    import React, { useState } from "react";
    
    export default function GuessApp() {
      const [inputValue, setInputValue] = useState("");
    
      function onChange(e) {
        const value = e.target.value;
        if (/^[a-zA-Z]*$/.test(value)) {
          setInputValue(value);
        }
      }
    
      return (
        <form className="border">
          <input
            className="border border-black w-8 h-8 text-center uppercase"
            type="text"
            maxLength="1"
            value={inputValue}
            onChange={onChange}
          />
        </form>
      );
    }