How can I set material-ui TextField to accept only Hexidecimal characters

12,352

Solution 1

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

Solution 2

        <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" />

Solution 3

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

Share:
12,352
Zotov
Author by

Zotov

Updated on June 04, 2022

Comments

  • Zotov
    Zotov almost 2 years

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