Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a pattern to a TextField to only allow specific characters

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

like image 786
Keith Withall Avatar asked Mar 20 '19 10:03

Keith Withall


1 Answers

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);

Edit TextField pattern

like image 125
Ryan Cogswell Avatar answered Nov 18 '22 08:11

Ryan Cogswell