SharadH
SharadH

Reputation: 95

Material-ui 4.9.5 TextField attribute "required" not working

I have a simple TextField wth 'required' attribute. It generated 'required=""' in the html 'input' element, and hence does not trigger the required error message(I believe that is the intended mechanism for the TextField 'required' attribute). Please see the code below and the codesandbox

import React from "react";
import { TextField, Button } from "@material-ui/core";

export default function App() {
   return (

   <div className="App">
       <TextField required label="LoftyPine" />
       <Button variant="contained" onClick={() => {}}>
       Validate
      </Button>
   </div>

   );
}

Same CodeSandbox

Upvotes: 5

Views: 12520

Answers (2)

SharadH
SharadH

Reputation: 95

Thanks to @Ryan for pointing the way. There is another variation without mixing any html like form , by using the inputRef prop of the TextField component, which creates? and passes a ref to the input element. If we have multiple TextField s, the con is you have to reportValidity on each element, but the pro is you have more control on sequence of validation and other input level functions.

`import React from "react";
import { TextField, Button } from "@material-ui/core";

export default function App() {

  let myRef = {}
  return (
    <div className="App">
      <TextField required inputRef={myRef} label="LoftyPine" />
      <Button variant="contained" onClick={() => {myRef.current.reportValidity()}}>
        Validate
      </Button>
    </div>
  );
}`

WIthoutHtmlForm

Upvotes: 0

Ryan Cogswell
Ryan Cogswell

Reputation: 80976

In order to trigger the browser's default required error message, the TextField needs to be in a form, and you need to trigger the validation. There are several ways to trigger the validation such as clicking a button with type="submit" or calling reportValidity on the form.

Here is an example showing calling reportValidity:

import React from "react";
import { TextField, Button } from "@material-ui/core";

export default function App() {
  const formRef = React.useRef();
  return (
    <div className="App">
      <form ref={formRef}>
        <TextField required label="LoftyPine" />
        <Button
          variant="contained"
          onClick={() => formRef.current.reportValidity()}
        >
          Validate
        </Button>
      </form>
    </div>
  );
}

Edit Required TextField

Upvotes: 4

Related Questions