I want to only allow specific characters to be entered into a Material-UI TextField. I have seen different examples that I have tried but I can't get any of them to work. In my last try I cut everything back to the bare minimum and had this
<TextField
inputProps={{ pattern: "[a-z]" }}
/>
It seems as though the pattern is just being ignored.
Is this still a valid way to apply a pattern
Thank you to anyone that can help me
Below is an example showing this working. The "pattern" attribute on input won't prevent invalid characters from being entered, but it will mark the input with the ":invalid" pseudoclass. Here is one resource where you can read more. I have added some styling so that you can tell the pattern is working.
If you want to prevent invalid characters from being entered, then you can see my previous answer for an example (based on the demos) using react-text-mask: How can I set material-ui TextField to accept only Hexidecimal characters
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import { withStyles } from "@material-ui/core/styles";
const styles = {
input: {
"&:invalid": {
border: "red solid 2px"
}
}
};
function App({ classes }) {
return (
<TextField
inputProps={{ className: classes.input, pattern: "[a-z]{1,15}" }}
/>
);
}
const StyledApp = withStyles(styles)(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<StyledApp />, rootElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With