[英]How can I set material-ui TextField to accept only Hexidecimal characters
I want my TextField to accept only the values from 0-9 and letters AF.我希望我的 TextField 只接受 0-9 和字母 AF 的值。 Thanks.
谢谢。
<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" />
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:这是我使用仅接受最多 8 个十六进制字符的 react-text-mask 组合在一起的示例(使用格式化的输入演示代码作为起点):
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 RegexTextField 组件
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 https://codesandbox.io/s/materialui-regextextfield-sd6l8?file=/src/App.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.