Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent sending empty values of form when submitting?

I have an Ant form in a React app, where some fields are required and some not. My problem is that when not required field is empty, backend sends the validation error. My question is, is there a way to NOT TO SEND the value of not required field if there is no value?

Screenshot of the current object that is sent:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code for form submission:

  const submitHandler = async (val: any) => {
    setLoading(true);
    try {
      let res: any = await API.put(`recipients/${pid}`, {
        ...val,
        user_id: loggedInUser.id,
        type: type,
      });
      setLoading(false);
      message.success("Benutzer erfolgreich aktualisiert");
      setError("");
    } catch (error: any) {
      setLoading(false);
      setError(error?.response.data.message);
      message.error(error?.response.data.message);
    }
  };

>Solution :

You can remove properties with empty value from that val before sending it to the back end. A way is doing it so:

let res = await API.put(`recipients/${pid}`, {
  ...Object.fromEntries(Object.entries(val).filter(([_, v]) => v)),
  user_id: loggedInUser.id,
  type: type,
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading