Reputation: 285
I want my TextField to accept only the values from 0-9 and letters A-F. Thanks.
Upvotes: 5
Views: 21435
Reputation: 2046
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
Upvotes: 1
Reputation: 61
<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" />
Upvotes: 6
Reputation: 80976
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:
Upvotes: 3