reactjs - Material-UI:限制 TextField 中的特定特殊字符
问题描述
如何验证或不允许[^%<>\\$'"]
在 Material-UI 上输入以下特殊字符TextField
。
以下是我现有的代码。
const useStyles = makeStyles((theme) => ({
textField: {
marginRight: theme.spacing(1),
width: 500,
},
FormLabelHeader:{
fontSize: '20px',
width: 500,
},
})
enter code here
const txtNameChange = (e) =>
{
setpersonDetails(prevState =>({
...prevState,
'NAME' : e.target.value
}))
}
.....
<FormControl>
<FormLabel className = {style.FormLabelHeader}>Add</FormLabel><br/>
<TextField className = {style.textField} label='NAME' name = 'NAME' variant='outlined' autoComplete='off' onChange={txtNameChange}/><br />
</FormControl>
解决方案
我怎样才能进行验证
helperText
您可以通过设置和的error
道具验证值后提供错误消息TextField
:
const [name, setName] = useState("");
const [error, setError] = useState("");
const onChange = (e) => {
const newValue = e.target.value;
if (!newValue.match(/[%<>\\$'"]/)) {
setError("");
} else {
setError("Unforbidden character: %<>$'\"");
}
setName(newValue);
};
return (
<TextField
value={name}
onChange={onChange}
helperText={error} // error message
error={!!error} // set to true to change the border/helperText color to red
/>
);
或不允许进入
由于您已经TextField
在代码中控制了 的值,因此如果验证失败,请不要更新状态:
const onChange = (e) => {
const newValue = e.target.value;
if (!newValue.match(/[%<>\\$'"]/)) {
setError("");
setName(newValue); // only set when successful
} else {
setError("Unforbidden character: %<>$'\"");
}
};
推荐阅读
- python - 视频流失真 QImage
- python - 使用 pyexcelerate 在 excel 中添加图像
- python - SQLAlchemy:UnicodeEncodeError:'ascii'编解码器无法编码字符(忽略数据库引擎编码?)
- java - Java链接列表插入方法没有重复?
- java - 如何使用休眠投影获取单列值
- swift - 为什么在显示 NSAlert 后没有任何效果?
- amazon-web-services - AWS 教育初学者账户不再有效
- python-3.x - 在我的程序中尝试使用 append、empty() 和 pop 并且没有迭代来反转堆栈时出现 RecursionError
- python - Python JSON 抓取 - 如何处理缺失值?
- node.js - 构建节点应用程序时,我如何解决 Azure Devops Pipeline 上的构建失败