How to handle vue js form validation with Laravel validation rules



Image not found!!

Handling form validation in Vue.js with Laravel validation rules involves a combination of client-side and server-side validation. Laravel provides robust server-side validation, and Vue.js can be used for client-side validation to enhance the user experience. Here's a general guide on how to achieve this:

1. Laravel Backend Setup:

a. Create Validation Rules in Laravel:

Define your validation rules in the Laravel controller method that handles form submission.

php
use Illuminate\Http\Request; public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users|max:255', // Add more validation rules as needed ]); // Process the data and store it in the database // ... return response()->json(['message' => 'Data successfully saved']); }

b. Return Validation Errors:

Ensure that if validation fails, Laravel returns the appropriate error messages. You can manually handle validation errors or use Laravel's built-in validation error responses.

php
use Illuminate\Validation\ValidationException; protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) { throw new ValidationException($validator, response()->json(['error' => $validator->errors()], 422)); }

2. Vue.js Frontend Setup:

a. Create the Vue Component:

Create a Vue component for your form.

html
<template> <form @submit.prevent="submitForm"> <!-- Form fields --> <div> <label for="name">Name:</label> <input v-model="formData.name" type="text" id="name"> <span v-if="errors.name" class="error">{{ errors.name[0] }}</span> </div> <!-- Add more form fields with similar structure --> <button type="submit">Submit</button> </form> </template> <script> export default { data() { return { formData: { name: '', // Add more form fields }, errors: {}, }; }, methods: { async submitForm() { try { const response = await this.$axios.post('/api/your-endpoint', this.formData); console.log(response.data.message); // Handle success (e.g., show success message) } catch (error) { if (error.response.status === 422) { this.errors = error.response.data.error.errors; } else { // Handle other errors } } }, }, }; </script>

In this example, we use the v-model directive for two-way data binding and show validation errors below each input field.

3. Additional Considerations:

  • Make sure to include Vue and Axios in your project if you haven't already.
  • Adjust the form fields and validation rules according to your requirements.
  • Customize the error handling and messages based on your application needs.

This setup allows you to utilize Laravel's powerful server-side validation while enhancing the user experience with Vue.js for client-side validation.