I work on an application, I have to manage the frontend part with vue.js and the backend part with express.js and MySQL.
I need to handle requests in VueJS: Fetch API.
- The page in question is the registration.
I want The form data will be validated by the front-end before being sent to the back-end.
Code :
<script>
export default {
name: "FormSuscribe",
data() {
return {
first_name: "",
email: "",
password_key: "",
};
},
methods: {
signup() {
fetch("http://localhost:3000/api/auth/signup", {
method: "POST",
//--Header--//
headers: {
Authorization: "Bearer ",
Accept: "application/json",
"Content-Type": "application/json",
},
//---Body--//
body: JSON.stringify({
name: this.name,
email: this.email,
password: this.password,
}),
});
},
},
};
</script>
<template>
<main>
<section >
<div >
<div >
<div >
<img
src="@/assets/signup-image.jpg"
alt="Office"
/>
</div>
<div >
<form method="post" @submit="signup">
<div >
<div >
<input
id="first_name"
name="username"
placeholder="Nom"
v-model="first_name"
/>
</div>
</div>
<div >
<div >
<input
type="email"
id="email"
name="email"
placeholder="[email protected]"
v-model="email"
/>
</div>
</div>
<div >
<div >
<input
type="password"
id="password"
name="password"
placeholder="**********"
v-model="password_key"
/>
</div>
</div>
<div >
<div >
<button type="button" >register</button>
<a href="">Forgot password</a>
<p>
You already have an account <a href="#">Connect</a>
</p>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<div >
<img
src="@/assets/icon-left-font-black.webp"
alt="Brand "
/>
</div>
</main>
</template>
CodePudding user response:
In signup()
method before making an API call, you can check for the required
fields. If there is no data in the fields don't make an API call.
For Ex :
signup() {
if (this.first_name && this.email && this.password_key) {
// Make an API call
} else {
// Show error messages for each field validity.
}
}
You can also use HTML5 required
attribute if you are only looking for the required field validation.
Demo :
new Vue({
el: '#app',
data: {
first_name: '',
email: '',
password_key: ''
},
methods: {
signup() {
console.log('form submitted!');
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form @submit="signup">
First Name :<input type="text" v-model="first_name" required/><br>
Email :<input type="text" v-model="email" required/><br>
Password :<input type="password" v-model="password_key" required/><br>
<button type="submit">Submit</button>
</form>
</div>
CodePudding user response:
You can use vee-validate
package to validate you data in front end part
here is an example :
https://codesandbox.io/s/y3504yr0l1?initialpath=/#/form&module=/src/components/Form.vue