Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading