Home > Software design >  setting up custom error validation in react
setting up custom error validation in react

Time:11-20

I am trying to create some custom error validation in React

I have a values obj in state and an error obj in state that share the same keys

  const [values, setValues] = useState({
    name: "",
    age: "",
    city: ""
  });

  const [err, setErr] = useState({
    name: "",
    age: "",
    city: ""
  });

i have a very simple handle change and an onSubmit which i want to run my custom validator function inside

  const handleChange = (e) => {
    setValues({
      ...values,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    validateForms();
  };

in my validateForms function my theory is since both my pieces of state share the same keys I am trying to see if any of those values === '' if yes match is the same key in the err obj and set that respective value to the error and then do other stuff in JSX

  const validateForms = () => {
    for (const value in values) {
      if (values[value] === "") {
        setErr({
          ...err,
          value: `${value} is a required field`
        });
      }
    }
  };

I definitely feel like I'm not using setErr properly here. Any help would be lovely. link to sandbox: https://codesandbox.io/s/trusting-bartik-6cbdb?file=/src/App.js:467-680

CodePudding user response:

You have two issues. First, your error object key needs to be [value] rather than the string value. Second, you're going to want to use a callback function in your state setter so that you're not spreading an old version of the error object:

const validateForms = () => {
  for (const value in values) {
    if (values[value] === "") {
      setErr(err => ({
        ...err,
        [value]: `${value} is a required field`
      }));
    }
  }
};

A more intuitive way to set errors might be to accumulate them all and just set the error state once:

const validateForms = () => {
  const errors = {};
  for (const value in values) {
    errors[value] = values[value] === "" ? `${value} is a required field` : "";
  }
  setErr(errors);
};
  • Related