首页 > 解决方案 > 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>

标签: reactjsmaterial-ui

解决方案


我怎样才能进行验证

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: %<>$'\"");
  }
};

编辑 66848152/material-ui-restrict-specific-special-characters-in-textfield


推荐阅读