#Ignoring empty models

9 messages · Page 1 of 1 (latest)

versed bone
#

Hi there, I want to use Inertia with Vue. Let's say I have a form, where I can add persons to the DB. I also have a button that allowes you to add multiple persons at once.
I know how to send the data to Laravel via Inertia and I know how to validate arrays. But for example I add some Persons and I click on 'Add new person' and leave all that person's fields empty. How do I ignore that or multiple left empty ones? ```js
<template>
<div>
<form @submit.prevent="handleSubmit">
<div v-for="(person, index) in people" :key="index">
<label>Name:</label>
<input type="text" v-model="person.name">
<label>Email:</label>
<input type="email" v-model="person.email">
</div>
<button @click.prevent="addPerson">Add Person</button>
<button type="submit">Submit</button>
</form>
</div>
</template>

<script setup>
import { ref } from 'vue';

const people = ref([{ name: '', email: '' }]);

const addPerson = () => {
people.value.push({ name: '', email: '' });
};

const handleSubmit = () => {
// Handle form submission, access the data in people array
console.log(people.value);
};
</script>```

stark frost
versed bone
#

for example you click on Add Person, and don't fill in any of the new appeared fields, you'd want to skip them with validating, since there's nothing in it

zealous frigate
#

That's precicely what M4tr1ck is saying, the input is prepared before validation, so there you could filter out empty values, then afterwards it's being validated

#

But this kinda looks like fixing user-error. I'd personally just ignore it, let the user fill out the form properly. So no filtering / modifying of the submitted data, just as-is. Validate the fields are correct, if they're incorrect you'll get validation errors, show that to the user

stark frost
#

Thanks Robert.

Before validation you can prepare your input and remove all empty values inside the same request class.

versed bone
zealous frigate
# versed bone ah so if they add another row of fields and don't add any data it's their fault ...

Yeah, that would be my go-to. UX-wise it's a little "downgrade", they click submit, get an error back, click the button to remove the empty row, submit again. But IMHO it makes your code way less complicated, easier to work with, no need to account for edge-cases. Obviously you're free to do what you want, if it's a requirement that an empty person row should be submitted and then discarded then you'd probably want to filter that out prior to validation. It's just, if you have validation errors, the empty row wouldn't be present