Laravel validation now in Vue
Hello everyone , this is my first article in medium and i hope you love it .
Today i will talk about a pretty package for validation in vue js vee-validate package make you can use some short expressions like laravel and support localization
vee-validate now make you can use simple rules to do validation in Vue js and support Vutify and other libraries
link in github :
let ‘s start with some examples :
first use pure vue js with vee-validate
installation with npm :
npm install vee-validate --save
for import :
import Vue from 'vue';
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);
or use CDN : use jsdelivr or unpkg
<!-- jsdelivr cdn -->
<script src="https://cdn.jsdelivr.net/npm/vee-validate@latest/dist/vee-validate.js"></script>
<!-- unpkg -->
<script src="https://unpkg.com/vee-validate@latest"></script>
for import in cdn mode use
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vee-validate@latest/dist/vee-validate.js"></script> <script>
Vue.use(VeeValidate); // good to go.
// use vue instance here
</script>
we can write first example using email validation like this
email :
<input v-validate="'required|email'" name="email" type="text" >
<span style="color:red;">
{{ errors.first('email') }}
</span>
run the code in code pen : https://codepen.io/mohammed_shopan/pen/BEOZLL
also you can use it with Vuetify like this example :
run in code pen : https://codepen.io/mohammed_shopan/pen/mgGqqP
<form name="myform" id="myform" >
<v-text-field
v-model="email"
prepend-icon="email"
hint="write your email"
name="email"
label="e-mail"
v-validate="'required|email'"
:error-messages="errors.first('email')"
></v-text-field>
<v-text-field
v-model="title"
prepend-icon="title"
hint="write your title"
counter="25"
name="title"
label="Title"
v-validate="'required|max:25'"
:error-messages="errors.first('title')"
>
</v-text-field>
<v-btn v-on:click.stop="sendData" >
Send
</v-btn>
<form>
we use : v-validate=”’required|email’” for validate the email and use
v-validate="'required|max:25'"
for validaide title with max 25 cand and use counter=”25” prop to calc char to the user
code for sendData function
sendData (){
this.$validator.validate().then(valid => {
if (!valid) {
// do stuff if not valid.
alert('you hava some invalid data \):');
} else {
// do if valid
alert('validation success \(: \(: ');
}
});
}
we use the this.$validator.validate() promise to know if data user enter valid or not if the data is valid we submit this form or send the data to api
also you can custom the event who fire the validation
// default events is input you make it 'change'Vue.use(VeeValidate,{
events : 'input'
});
change event : https://baianat.github.io/vee-validate/guide/events.html
Vue.use(VeeValidate,{
events : 'change'
});
Vee validate has a lot of amazing features and support and an amazing documentation .