简体   繁体   中英

Form Validation in material UI React - how to implement form validation for dropdown list

I am new to react and I am using material-ui from validation am trying to validate the form by getting the id of HTML elements. This works out Ok but whenever I try to validate a dropdown list and error occurs

Cannot read property 'length' of undefined. It is not able to read the id of "Status". How do I resolve this?

Here is the code:

          <TextField
            label="Title"
            variant="outlined"
            size="small"
            name="Title"
            id="Title"
            placeholder="Enter the Title of the Best Practice"
            onChange={handleChange("Title")}
            defaultValue={values.Title}
            style={{ width: "80%" }}
          />
          <label id="title" style={{ visibility: "hidden", color: "red" }}>
            Title must be atleast 5 characters long
          </label>
          <br />

          <TextField
            placeholder="Enter the details of the Best Practice"
            label="Details of Best Practice"
            id="Details"
            size="small"
            name="Details"
            onChange={handleChange("Details")}
            defaultValue={values.Details}
            style={{ width: "80%" }}
            variant="outlined"
            multiline
            rows={4}
            rowsMax={8}
          />
          <label id="details" style={{ visibility: "hidden", color: "red" }}>
            Details of Best Practice must be atleast 10 characters long
          </label>
          <br />

          <TextField
            placeholder="What is the Best Practice?"
            label="What is the Best Practice"
            size="small"
            id="What"
            name="What"
            onChange={handleChange("What")}
            defaultValue={values.What}
            style={{ width: "80%" }}
            variant="outlined"
            multiline
            rows={4}
            rowsMax={8}
          />
          <label id="what" style={{ visibility: "hidden", color: "red" }}>
            What is the Best Practice must be atleast 10 characters long
          </label>

          <br />

          <TextField
            placeholder="Why was the Best Practice Implemented"
            label="Why was the Best Practice Implemented"
            size="small"
            name="Why"
            id="Why"
            onChange={handleChange("Why")}
            defaultValue={values.Why}
            style={{ width: "80%" }}
            variant="outlined"
            multiline
            rows={4}
            rowsMax={8}
          />
          <label id="why" style={{ visibility: "hidden", color: "red" }}>
            Why was the Best Practice implemented must be atleast 10 characters
            long
          </label>

          <br />
          <TextField
            placeholder="How was the Best Practice Implemented"
            label="How was the Best Practice Implemented"
            size="small"
            name="How"
            id="How"
            onChange={handleChange("How")}
            defaultValue={values.How}
            style={{ width: "80%" }}
            variant="outlined"
            multiline
            rows={4}
            rowsMax={8}
          />
          <label id="how" style={{ visibility: "hidden", color: "red" }}>
            How was the Best Practice implemented must be atleast 10 characters
            long
          </label>

          <br />
          <FormControl id="Status" style={{ width: "80%" }} size="small">
            <InputLabel
              htmlFor="Implementation Status"
              id="Status"
              style={{
                marginLeft: 10,
                top: "50%",
                transform: "translate(0,-50%"
              }}
            >
              Implementation Status
            </InputLabel>
            <Select
              labelId="Implementation Status"
              name="Status"
              id="Status"
              onChange={handleChange("Status")}
              defaultValue={values.Status}
              variant="outlined"
              inputProps={{
                id: "Implementation Status",
                name: "age"
              }}
            >
              <MenuItem value="Implemented">Implemented</MenuItem>
              <MenuItem value="Implementation in Progress">
                Implementation in Progress
              </MenuItem>
              <MenuItem value="Not Implemented">Not Implemented</MenuItem>
            </Select>
          </FormControl>
          <label id="status" style={{ visibility: "hidden", color: "red" }}>
            Implementation Status cannot be blank
          </label>

Here is the code for the validation:

export class FormUserDetails extends Component {
  continue = e => {
    e.preventDefault();

    if (document.getElementById("Title").value.length < 5) {
      document.getElementById("title").style.visibility = "visible";
      document.getElementById("Title").style.border = "1px solid red";
      // keep form from submitting
    } else if (document.getElementById("Details").value.length < 10) {
      document.getElementById("details").style.visibility = "visible";
      document.getElementById("Details").style.border = "1px solid red";
      // keep form from submitting
    } else if (document.getElementById("What").value.length < 10) {
      document.getElementById("what").style.visibility = "visible";
      document.getElementById("What").style.border = "1px solid red";
      // keep form from submitting
    } else if (document.getElementById("Why").value.length < 10) {
      document.getElementById("why").style.visibility = "visible";
      document.getElementById("Why").style.border = "1px solid red";
      // keep form from submitting
    } else if (document.getElementById("How").value.length < 10) {
      document.getElementById("how").style.visibility = "visible";
      document.getElementById("How").style.border = "1px solid red";
      // keep form from submitting
    } else if (document.getElementById("Status").value.length < 1) {
      document.getElementById("status").style.visibility = "visible";
      document.getElementById("Status").style.border = "1px solid red";
      // keep form from submitting
    } else {
      // else form is good let it submit, of course you will
      // probably want to alert the user WHAT went wrong.

      this.props.nextStep();
    }
  };

Everything up till status works fine. The moment we get to status, it pops the error

I'm not sure why you're using pure js code in ReactJS, Material-UI gives you the handy way to validate the form, also you write hard code to change the color, and alot of duplication, which isn't efficient. Let's use the cool way which provides Material why not use that instead, Validating form is easy.

there is how we detect the value of the dropdown if it's null show error, otherwise, keep the default color, we use React state to keep the value here is the code I wrote for your solution:

export default function App() {
  const classes = useStyles();

  // DropDown State
  const [age, setAge] = React.useState("");
  const [error, setError] = React.useState(false);

  /*  Keeping value when selected **/
  const handleChange = event => {
    setAge(event.target.value);
  };

  // Showing Error
  const submitHandler = () => {
    console.log(age === "");
    if (age === "") {
      setError(true);
      return;
    }
    setError(false);

    // submitting logic here..
  };

  return (
    <div className={classes.root}>
      <FormControl className={classes.formControl}>
        <InputLabel shrink id="demo-simple-select-placeholder-label-label">
          Age
        </InputLabel>
        <Select
          labelId="demo-simple-select-placeholder-label-label"
          id="demo-simple-select-placeholder-label"
          value={age}
          onChange={handleChange}
          displayEmpty
          className={classes.selectEmpty}
          error={error}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
        <FormHelperText>Label + placeholder</FormHelperText>
      </FormControl>
      <Button
        onClick={submitHandler}
        variant="contained"
        className={classes.button}
      >
        Send
      </Button>
    </div>
  );
}

Here is the Demo code: codesandbox , here is the official docs link .

在此处输入图像描述

I Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM