Laravel is an advanced PHP framework built perfectly for web artisans. It helps creating robust APIs and optimized web applications. Further, the framework is very developer friendly as it provides different features to ease out various functional operations.
Handling request validation is one of the most important part of any web application. Many of us know that there are multiple ways to validate request in Laravel, in which one is the very popular with Vue validation.
On the other side, VueJS is increasingly getting popular among the front end community not because of its impressive functionalities, but because of its official support with Laravel as well.
While building an interactive web application, one most important thing for developers to take care of is the Vue form validation. You can either apply form validation yourself, or could use some plugins to do the job.
Less Hassle. More Development.
Let us future-proof your hosting requirements. You focus on building your applications.
So in this tutorial, I will demonstrate how to validate data in Laravel using Vue validation.
Prerequisites
For the purpose of this Vue form validation tutorial, I assume that you have a Laravel application installed on a web server. My setup is:
- Laravel 5.5
- PHP 7.x
- MySQL
- Npm
For optimized developer stack, I have installed my Laravel application on a Cloudways managed server which is regarded as a perfect platform for hosting Laravel project. You can also sign up for a free Cloudways account easily and can setup your application within few minutes.
Install Npm
Getting started with Vue form validation, the first step is the installation of Node.js with NPM.
So install NPM first and go to the project’s folder and paste the following command in SSH terminal.
npm init npm install
The Routes
Now the next step is to create routes in Vue controller for validation pages like index, store function and others.
Route::get('vuevalidation/form', 'VueController@index'); Route::post('vuevalidation/form', 'VueController@store');
You Might Also Like: Understanding Routing in Laravel
The Controller
To create a VueController that handles various logical operation, just copy and paste the below given command:
php artisan make:controller VueController
Store ()
After creating the controller successfully, open it and paste the following code under the store function.
$request->validate([ 'name' => 'required', 'comments' => 'required' ]); return response()->json(['success'=>'Done!']);
Index ()
return view('vuevalidation-form');
View
Once setting up controller function successfully, now it is time to create view files inside the folder resources/views/. Give it a name as vuevalidation-form.blade.php and paste the below given code:
<!DOCTYPE html> <html> <head> <title></title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" > <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-8 col-sm-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Simple Vuejs Form Validation with Laravel - ItSolutionStuff.com</div> <div class="panel-body" id="app"> <form method="POST" action="/vuejs/form" class="form-horizontal" @submit.prevent="onSubmit" > {{ csrf_field() }} <div :class="['form-group', allerros.name ? 'has-error' : '']" > <label for="name" class="col-sm-4 control-label">Name</label> <div class="col-sm-6"> <input id="name" name="name" value="" autofocus="autofocus" class="form-control" type="text" v-model="form.name"> <span v-if="allerros.name" :class="['label label-danger']">@{{ allerros.name[0] }}</span> </div> </div> <div :class="['form-group', allerros.comments ? 'has-error' : '']" > <label for="comments" class="col-sm-4 control-label">Message</label> <div class="col-sm-6"> <input id="comments" name="comments" class="form-control" type="comments" v-model="form.comments"> <span v-if="allerros.comments" :class="['label label-danger']">@{{ allerros.comments[0] }}</span> </div> </div> <span v-if="success" :class="['label label-success']">Record submitted successfully!</span> <button type="submit" class="btn btn-primary"> Send </button> </form> </div> </div> </div> </div> </div> <script type="text/javascript"> const app = new Vue({ el: '#app', data: { form: { name : '', comments : '', }, allerros: [], success : false, }, methods : { onSubmit() { dataform = new FormData(); dataform.append('name', this.form.name); dataform.append('comments', this.form.comments); console.log(this.form.name); axios.post('/vuevalidation/form', dataform).then( response => { console.log(response); this.allerros = []; this.form.name = ''; this.form.comments = ''; this.success = true; } ).catch((error) => { this.allerros = error.response.data.errors; this.success = false; }); } } }); </script> </body> </html>
Once pasting the above code, run the application in preferred browser and check validation.
Vue Validation Plugins
If you don’t like setting up validation manually, there are also some pre-made Vue validation libraries and plugins available in the market which could save your time and ease out several operations.
Since there are many validation plugins available out there, I recommend you to choose anyone from the given below:
Vue-validator:
Developed by Kazuya Kawaguchi, Vue Validator is the most popular one and is developed by the core members of VueJS. But it is not compatible with Vue 2 as of yet.
Vue-form-generator:
This is also one of the great plugin in VueJS form validation stack, as it also builds interactive forms along with validation.
Vee-validate:
Vee-validate is new module for validation but its compatibility with Vue1 and Vue2 makes it a much better choice for validation as of yet. This Vue validation library is very handy for the developers and thus I will be using this in the below tutorial also.
Vee-Validate
This VueJS form validation plugin is very lightweight and allows you to easily validate input fields. Using it doesn’t require anything fancy, as all the work goes with HTML and is quite easy. You just have to specify type of validation for each input, as what value changes should occur with the validation. You will then get the notification of each occurring errors in the field.
While most of the time validations are configured to occur automatically, however you can use customized validation in specific places also. The validator object is a standalone object and has no dependencies.
This Vue validator plugin has currently 20 validation rules and works pretty same like Laravel’s validation syntax.
Installation
Vee-validate is only available on NPM currently, but it is expected to move forward soon.
So to get the compatible plugin version of Vue 2, I have to execute the following command:
npm install vee-validate@next --save
Then, I will authorize Vue to use it in my JavaScript.
import Vue from 'vue'; import VeeValidate from 'vee-validate'; Vue.use(VeeValidate);
Basic Example Form Validation
Now to validate an input, attach v-validate directive and define validation rules inside the data-rules attribute.
<div class="form-group" :class="{'has-error': errors.has('email') }" > <label class="control-label" for="email">Email</label> <input v-model="email" v-validate="email" data-rules="required|email" class="form-control" type="email" placeholder="Email"> <p class="text-danger" v-if="errors.has('email')">{{ errors.first('email') }}</p> </div>
Errors
Notice here, that error object is used to check errors in input and notify the developers about it. It is created automatically by plugin and you can change its name whenever is needed.
The error object provides you few methods to render errors:
- first(‘field’): Fetches the first error message associated with that field.
- collect(‘field’): Fetches all error messages associated with that field.
- has(‘field’): Checks if there are any errors associated with that field.
- all(): Gets all error messages.
- any(): Checks if there are any errors.
You Might Also Like: Simplify Laravel Error Logging with PHP Rollbar Integration
Q: Vuelidate vs vee-validate: Which one to use?
A: Both of the plugins vuelidate and vee-validate are used for validating requests, but both works with some different procedures. Contrasting to vuelidate, vee-validate is pretty simple to use. As it doesn’t requires any additional implementation of custom components for field validation, and just requires directives to complete the process.
Q: How many Vue validation plugins are there?
A: There are number of Vue form validation plugins available out there, but the top three which are mostly used by the developers are: Vue-validator, Vue-form generator and Vee-validate.
Amongst them, vee-validate is the most favored choice of developers, as it is fully compatible with both Vue1 and Vue2 version.
Q: How to clear errors object in vee-validate?
A: To clear error objects in vee-validate, you can use either of these two methods i.e “this.errors.clear()” and “this.$validator.clean()”. Both of these methods perform the same operation and clears all the errors objects in the form requests.
Q: How to fix ‘custom validation rules not working’ problem in vee-validate?
A: You can easily define custom rules in vee-validate, but those rules must adhere to a certain structure or contract. Always try to use double quotes in your markups (string notations) like this:
v-validate = “password”
Or, you could also use object notation when you have more than one complex rules.
v-validate = “{password: true}”
Conclusion
So in this article, I have demonstrated in detail how to validate data using the Vue validation. The article covers two methods of validating data with Vue, one is the manual process and the other one is through premade plugins. It is up to you which one suits your validation demands.
If you still have more questions about this article, do write your queries below in the comments section.
Shahzeb Ahmed
Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]