'How to wait for user input in TextField before it turns red with Material UI

I am making a simple sign up page on react and using Material UI. But the user would always get the red TextField with my code.

How to make it wait for the user to first try to input then it would give a feedback (either red or not)?

a picture of the sign up page

This is my current code

         <Box
            component="form"
            sx={{ '& > :not(style)': { m: 1, width: '25ch' } }}
            noValidate
            autoComplete="off"
          >
            <TextField
              id="outlined-basic"
              label="First Name"
              onChange={(event) => setFirstName(event.target.value)}
              variant="outlined"
              error={!firstName}
              required
            />
            <TextField
              id="outlined-basic"
              label="Last Name"
              onChange={(event) => setLastName(event.target.value)}
              variant="outlined"
              error={!lastName}
              required
            />
            <TextField
              id="outlined-basic"
              label="Home Number"
              onChange={(event) => setHomeNumber(event.target.value)}
              variant="outlined"
              type="tel"
              error={!homeNumber}
              required
            />
            <TextField
              id="outlined-basic"
              label="Address"
              onChange={(event) => setAddress(event.target.value)}
              variant="outlined"
              error={!address}
              required
            />
            <TextField
              id="outlined-basic"
              label="Email"
              onChange={(event) => setEmail(event.target.value)}
              variant="outlined"
              type="email"
              error={!email}
              required
            />
            <TextField
              id="outlined-password-input"
              label="Password"
              onChange={(event) => setPassword(event.target.value)}
              type="password"
              autoComplete="off"
              error={!password}
              required
            />
         </Box>


Solution 1:[1]

There are many ways to accomplish this requirement, I use one and make demo to you.

Code fragment

  1. Adding a verification state (there are three states) is the core of my solution.
  /**
   *  -1 : 'initial'
   *   0 : 'invalid'
   *   1 : 'valid'
   */
  const [validation, setValidation] = useState({
    firstName: -1,
    lastName: -1
  });
  1. Make a function that verifies whether the value of key are valid whenever the input on change, and gives the corresponding validation state.
  // Verify that the value for the key.
  const verify = (k, v) => {
    setValidation((prev) => ({ ...prev, [k]: v ? 1 : 0 }));
  };

  const handleInputOnChange = (e) => {
    const k = e.target.name;
    const v = e.target.value;
    // Verify that the value for the key.
    verify(k, v);
    setData((prev) => ({ ...prev, [k]: v }));
  };
  1. When a submit event or other event fires, check all validation states, set -1 to 0, and do the behavior you want.
  const handleOnSubmit = () => {
    // when event trigger, check all validation if invalid set value to 0, and make red prompt.
    verifyAll();

    // check invalid
    if (Object.values(validation).some((v) => v !== 1)) {
      // if there is invalid value, do something.
      console.error("Invalid value.");
    } else {
      // if pass send data.
      console.info(data);
    }
  };
  1. HTML style based on validation states, if 0, error and turn red.
        <TextField
          id="outlined-basic"
          name="firstName"
          label="First Name"
          onChange={handleInputOnChange}
          variant="outlined"
          // only validation === 0, changed to red(error).
          error={validation["firstName"] === 0}
          required
        />

Full code sample:

Edit TextField selectionStart

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