I want to validate two whole different forms in a single component. I created the two of them, configured the validations, the methods, data etc. Everything is fine, Moreover, both forms work acutally, but with a little problem. I wrote a little code to explain the problem I was having.
Here is my forms in the component.
<!-- First Form -->
<div>
<form @submit.prevent="submitFormFirst">
<div class="form-group">
<label>Name</label>
<input v-model="name" type="name" class="form-control" placeholder="Name" />
<small v-if="!$v.name.required && $v.name.$dirty">This field is required.</small>
</div>
<!-- Save Button -->
<button type="submit">Save Form 1</button>
</form>
</div>
<!-- Second Form -->
<div>
<form @submit.prevent="submitFormSecond">
<div>
<label>Surname</label>
<input v-model="surname" type="name" placeholder="Surname" />
<small v-if="!$v.surname.required && $v.surname.$dirty">This field is required.</small>
</div>
<!-- Save Button -->
<button type="submit">Save Form 2</button>
</form>
</div>
As you can see there are two different forms and they have their own submit buttons. Here is my data looks like;
data() {
return {
name: null,
surname: null,
};
And my validations...
validations: {
name: {
required,
},
surname: {
required,
}
}
And at the end, I created two methods. One for Form1 and one for Form2.
methods: {
submitFormFirst() {
if (!this.$v.$invalid) {
alert("First Form Submitted.");
let form = {
name: this.name,
};
console.log(form);
} else {
alert("First Form Error.");
}
},
submitFormSecond() {
if (!this.$v.$invalid) {
alert("Second Form Submitted.");
let form = {
surname: this.surname,
};
console.log(form);
} else {
alert("Second Form Error.");
}
},
}
So they have their own methods as well, they are totally seperated from each other, or I do think in this way... The problem is, when the page loads I immadiately go an try to type something in the first form's input and click "Save". It sends the "First Form Error" message with the alert. Then I type something in the second form's input and submit it, then it works, it prints the data in console and sends "Submitted." message. So when I start from the first form, I get an error. When I write and submit the second form, the problem disappears. Then I try the first form again, I see that it works too. The same scenario happens when I start from the second form. In other words, the first form I tried to submit gives an error, then I submit the other form. When I get back to the form I tried first, I see that it works too. What am I missing?