Home > Software engineering >  MUI Input field that only accepts letters, numbers, and dashes?
MUI Input field that only accepts letters, numbers, and dashes?

Time:04-09

How could I restrict a MUI input field to only accept letters, numbers, and dashes? So spaces and and symbols (*&^%$#@!,.<>{}[]) would be excluded.

More specifically, I'd like to allow anything that wouldn't cause a URL to crash, i.e. https://mywebsite.com/user-generated-string-here123.

Thanks!

CodePudding user response:

You could pass a handler to onKeyDown and check for the pressed key. Exclude if the pressed key is other than alphabet, number, or dash.

const ALPHA_NUMERIC_DASH_REGEX = /^[a-zA-Z0-9-] $/;
<TextField
  onKeyDown={(event) => {
    if (!ALPHA_NUMERIC_DASH_REGEX.test(event.key)) {
      event.preventDefault();
    }
  }}
/>

Alternatively, for controlled components, you can validate in onChange handler and update the state based on the value. This will also validate the value that is pasted in the text field and ignore if the condition doesn't pass.

const [value, setValue] = useState('');
<TextField
  value={value}
  onChange={(event) => {
    const value = event.target.value;
    if (value !== "" && !ALPHA_NUMERIC_DASH_REGEX.test(value)) {
      return;
    }
    setValue(value);
  }}
/>

Here's the link to the working demo in codesandbox.

  • Related