'Material-UI: Restrict specific special characters in TextField
How can I put a validation or not allow to enter the following special characters [^%<>\\$'"]
on the Material-UI TextField
.
Below are my existing codes.
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>
Solution 1:[1]
How can I put a validation
You can provide an error message after validating the value by setting the helperText
and error
props of TextField
:
const [name, setName] = useState("");
const [error, setError] = useState("");
const onChange = (e) => {
const newValue = e.target.value;
if (!newValue.match(/[%<>\\$'"]/)) {
setError("");
} else {
setError("Forbidden 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
/>
);
or not allow to enter
Since you've already controlled the value of TextField
in your code, simply don't update the state if the validation failed:
const onChange = (e) => {
const newValue = e.target.value;
if (!newValue.match(/[%<>\\$'"]/)) {
setError("");
setName(newValue); // only set when successful
} else {
setError("Forbidden character: %<>$'\"");
}
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Emanuel Unge |