I have this form and I want to make a validation on it but after i press submit button it doesn’t check validation and send new data to to another component.how can I fix validation?
thank you for your help.
this is html
code and form
:
<form @submit.prevent="handleSubmit">
<input type="text" required placeholder="name" v-model="firstName" />
<div v-if="firstNameError" class="error">{{ firstNameError }}</div>
<input type="text" required placeholder="lastname" v-model="lastName"/>
<div v-if="lastNameError" class="error">{{ lastNameError }}</div>
<input type="tel" required placeholder="mobilenumber" v-model="Mobile" />
<div v-if="MobileError" class="error">{{ MobileError }}</div>
<input type="tel" required placeholder="phonenumber" v-model="phone" />
<div v-if="PhoneError" class="error">{{ PhoneError }}</div>
<input type="text" required placeholder="address" v-model="address" />
<div v-if="addressError" class="error">{{ addressError }}</div>
<select v-model="gender">
<option value="female">خانم</option>
<option value="male">آقا</option>
</select>
<button>submit</button>
</form>
and script
code:
<script>
export default {
data() {
return {
firstName: "",
lastName: "",
Mobile: "",
phone: "",
address: "",
gender: "",
firstNameError: "",
lastNameError: "",
MobileError: "",
PhoneError: "",
addressError: "",
};
},
methods: {
handleSubmit() {
this.firstNameError =
this.firstName.length > 3
? ""
: "firstName must have at least 3 character";
this.lastNameError =
this.lastName.length > 3
? ""
: "lastName must have at least 3 character";
this.MobileError =
this.Mobile.length > 11
? ""
: "number must have at least 11 character";
this.PhoneError =
this.phone.length > 11
? ""
: "number must have at least 11 character";
this.addressError =
this.address.length > 5
? ""
: "address must have at least 5 character";
let project = {
firstName: this.firstName,
lastName: this.lastName,
Mobile: this.Mobile,
phone: this.phone,
address: this.address,
gender: this.gender,
};
console.log(project);
fetch("http://localhost:8000/forms", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(project),
})
.then(() => {
this.$router.push("/");
})
.catch((err) => console.log(err));
},
},
};
</script>