So last week I did a short video about using Vee-Validate with Vue3 and Ionic Framework new Vue Components.
I had someone ask me why didn't I used Vuelidate? There was no specific reason other than the last time I needed form validation, I had used Vee-Validate.
So what I have done here is reproduce the same example from the previous form/form validation post but this time using Vuelidate.
We bind all of this to the Vuelidate object using the useVuelidate hook. I could have used ref originally to avoid all of this, but I like working with a form object and not a bunch of fields.
Ref & Reactive:
ref() takes a primitive value and returns a reactive and mutable ref object
reactive() takes an object and returns a reactive proxy of the original
We need to have a function to handle when the user submits the form. In this situation we first trigger a validation of the form using vv.value.$touch(); if there is an error, we exit and do not submit the form.
// handle the submit of the form, only called// if the form is validconstonSubmit=()=>{vv.value.$touch();if (vv.value.$invalid)return;alert("Form Submitted "+JSON.stringify(fform,null,2));};
Since we are using a setup method, we need to return the appropriate functions and properties so they can be accessible in the template.
return{router:useRouter(),onSubmit,vv,};
Setting up My Form Template
In my form I have a few fields and since I am using Ionic components, initially I was concerned I would have to do some extra work but i didn't have to.
We have access to the model associated with the fields we created by using the vv object returned from the useVuelidate call; We use those models in our form
The great thing is since we are working with vue binding, the initial values that we set for our form fields get passed in through the model are set the input elements
Form fields have error objects associated with them, we can access the errors using the name of the field and the vuelidate object.
The code below renders the first error message associated with the input element named title
<p>{{ vv?.title?.$errors[0]?.$message }}</p>
Wrap Up
This was just a quick look at Vuelidate, I will be taking a deeper dive using the form and form validation functionality with a Modal Form video, blog post I am working on. In that example we will be using nested objects and more complex UI so it should be interesting to see how it works out.