Removing empty form fields from FormData
Browsers by default submit all the fields in a HTML form even when these fields are empty and not set by user. This could be undesirable if you validate your forms using JSON Schema, for example if you have required fields in your form your JSON Schema validator won't throw required
error for such empty fields. Not only this, if you don't want to write such empty values to your database, you need to sanitize data posted by such forms. Instead you can remove such fields before validation and submission to backend. Here is one way to do this in your form's submit event listener:
// removing empty fields before validation/submission
const myFormData = new FormData(myFormElement);
for (const [key, value] of Array.from(myFormData.entries())) {
if (value.length === 0) {
myFormData.delete(key)
}
}
Note that we use Array.from()
to avoid changing FormData during iteration which can result in keys not being deleted properly as explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#concurrent_modifications_when_iterating