4

I want my TextField to accept only the values from 0-9 and letters A-F. Thanks.

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
Zotov
  • 265
  • 1
  • 8
  • 20

3 Answers3

5
        <TextField
          id="text-field-1"
          placeholder="Enter text"
          type="text"
          value={state.alphanum}
          onChange={(event) => {
            const regex = /^([a-z0-9]){minLength,maxLength}$/i;
            if (event.target.value === '' || regex.test(event.target.value)) {
              setState({ ...state, alphanum: event.target.value });
            }
          }}
          variant="outlined" />
Nagarjun Ev
  • 51
  • 1
  • 2
3

See the Formatted Inputs portion of the documentation.

Here is an example I put together (using the formatted inputs demo code as a starting point) using react-text-mask that only accepts up to 8 hexidecimal characters:

Edit 6v444wnvp3

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
  • Note for future posterity: looks like formatted inputs is part of v3, but in v5 the link was updated to [this](https://mui.com/material-ui/react-text-field/#integration-with-3rd-party-input-libraries) – user3788955 Nov 17 '22 at 15:41
1

Sometimes all you want is just to have plain regex check to not allow some characters. No masks, no additional libs, no complicated refs etc.

const onlyAlphanumericRegex = /[^a-z0-9]/gi;

export default function App() {
  const [value, setValue] = React.useState("");

  return (
    <div className="App">
      <RegexTextField
        regex={onlyAlphanumericRegex}
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
}

RegexTextField component

export const matchNothingRegex = /(?!)/;

const RegexTextField = ({ regex, onChange, ...rest }) => {
  const handleChange = useCallback(
    (e) => {
      e.currentTarget.value = e.currentTarget.value.replace(regex, "");
      onChange(e);
    },
    [onChange, regex]
  );

  return <TextField onChange={handleChange} {...rest} />;
};

export default React.memo(RegexTextField);

RegexTextField.propTypes = {
  onChange: PropTypes.func.isRequired,
  regex: PropTypes.instanceOf(RegExp)
};

RegexTextField.defaultProps = {
  regex: matchNothingRegex
};

working example

https://codesandbox.io/s/materialui-regextextfield-sd6l8?file=/src/App.js

Hayk Safaryan
  • 1,996
  • 3
  • 29
  • 51