简体   繁体   中英

React js Validation textfield

I am trying to make a validation in reactjs. For example, I have a field called "name" and every time you input a name, this has to be bigger or equal to 2. It works when the name is smaller than 2, but if it's bigger than 2 the message still appears. Here is my code:

const [data, setData] = React.useState({
nameValid: true,
prenumeValid: true,
check_textInputChange: false,
name: "",
});

const handleValidUser = (val) => {
if (val.length >= 2) {
  setData({
    ...data,
    nameValid: true,
  });
} else {
  setData({
    ...data,
    nameValid: false,
    });
    }
  };
  const textInputChange = (val) => {
  if (val.length >= 2) {
    setData({
    ...data,
    name: val,
    nameValid: true,
    check_textInputChange: true,
  });
} else {
  setData({
    ...data,
    name: val,
    nameValid: false,
    check_textInputChange: false,
  });
}
 };


 <TextField
      type="text"
      variant="outlined"
      label="Nume"
      required
      fullWidth
      autofocus
      validate
      style={{ marginBottom: "1em" }}
      onChange={(val) => textInputChange(val)}
      onBlur={(e) => handleValidUser(e)}
    />
    {data.nameValid ? null : (
      <text>The name has to be at least 2 letters long</text>
    )}

Can you try changing

onChange={(val) => textInputChange(val)}

to this:

onChange={(e) => textInputChange(e.target.value)}

in function textInputChange you are passing event object instead of input value you have to change onchange handler from:

onChange={(val) => textInputChange(val)}

to

onChange={(val) => textInputChange(val.target.value)}

onChange has an event parameter, if you want to get the value of the TextField , you should write it as below.

const textInputChange = e => {
    const val = e.target.value;
    
    if (val.length > 2) {
        setData(...)
    } else {
        setData(...)
    }
}

return (
    <TextField
        ...
        onChange={textInputChange}
        onBlur={handleValidUser} // as well as onBlur
    />
)

I've created a codesandbox to demonstrate here .

Call the function as below will create an extra render every time the function is called. You should avoid it.

onChange={(val) => textInputChange(val)}

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