skip to Main Content

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


  1. 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>
      );
    }
    
    Login or Signup to reply.
  2. You should make it a controlled input.

    Use value={} and an useState 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.

    const { useState } = React;
    
    function GuessApp() {
    
        const [val, setVal] = useState('');
    
        function alphaOnly(e) {
            if (!e.target.value || /[a-zA-Z]/i.test(e.target.value)) {
                setVal(e.target.value)
            }
        }
    
        return (
            <form className="border">
                <input className="border border-black w-8 h-8 text-center uppercase" type="text" maxLength="1" value={val} onChange={alphaOnly}></input>
            </form>
        )
    }
    
    ReactDOM.render(<GuessApp />, document.getElementById("react"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search