Using Vue3 And Vuelidate for Forms and Form Validation
Tags: ionic, vue, tutorial, webdev
Published: 2020-09-26 23:14:24

####[See My Upcoming Book On Ionic & Vue JS](http://bit.ly/ionicvuebook)
---
So last week I did a short video about using [Vee-Validate](https://vee-validate.logaretm.com/v4/) with [Vue3](https://v3.vuejs.org/guide/introduction.html) and [Ionic Framework new Vue Components](https://ionicframework.com/docs/vue/quickstart).
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](https://vee-validate.logaretm.com/v4/).

So what I have done here is reproduce the same example from the previous form/form validation post but this time using [Vuelidate](https://vuelidate-next.netlify.app/#installation).

Code available at end of the post and please check out my [videos on Vue3 and Ionic Framework](https://www.youtube.com/playlist?list=PL2PY2-9rsgl2uKW0DB5FJ-YRCAG-JuSWN)

 
###Setting Up
>We are assuming you already have a vue3 project.

Install the library
```console
npm install @vuelidate/core@2.0.0-alpha.4
npm install @vuelidate/validators@2.0.0-alpha.2
```

Since I am using typescript, I needed to make this change in `shims-vue.d.ts`
```javascript
declare module '@vuelidate/core';
declare module '@vuelidate/validators';
```

###Setting up My Form Fields
First in the script area of my component, import the library
```javascript
import { useVuelidate } from "@vuelidate/core";
import { required, email } from "@vuelidate/validators";
```

In the setup function lets defined the form fields.
```javascript
// set fields and some initial values
const fform = reactive({
  title: "",
  body: "",
  emailAddress: "",
  gender: "MALE",
  save: true,
});
```
Next we will map the rules to the fields using rules from vuelidate that we imported.
```javascript
const rules = {
  title: { required },
  body: { required },
  emailAddress: { required, email },
  gender: {},
  save: {},
};
```
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
```javascript
const vv = useVuelidate(rules, {
  title: toRef(fform, "title"),
  body: toRef(fform, "body"),
  emailAddress: toRef(fform, "emailAddress"),
  gender: toRef(fform, "gender"),
  save: toRef(fform, "save"),
});
```
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.
```javascript
// handle the submit of the form, only called
// if the form is valid
const onSubmit = () => {
  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.
```javascript
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
```vuejs
<ion-item>
  <ion-label>Title</ion-label>
  <ion-input type="text" name="title" v-model="vv.title.$model" />
</ion-item>
```
####Form Initial Values
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
```vue
<ion-item>
  <ion-label>Gender</ion-label>
  <ion-select name="gender" v-model="vv.gender.$model">
    <ion-select-option>MALE</ion-select-option>
    <ion-select-option>FEMALE</ion-select-option>
  </ion-select>
</ion-item>
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/imvm0dqcacy5fn7kfi2y.png)
> See above where we setup form object

####Form Submit
No special magic with submitting the form, we just call our function and check for errors. If errors we can render them
```html
<form @submit.prevent="onSubmit" novalidate>
 ...
</form>
```
####Form Field Errors
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`
```html
<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.

###Source Code
{% github aaronksaunders/ionic-vue-validation-app %}

### Ionic Vue Videos
[![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/uanah6t3n4zd2vpac75f.png)](https://www.youtube.com/playlist?list=PL2PY2-9rsgl2uKW0DB5FJ-YRCAG-JuSWN)
[Click To View Playlist](https://www.youtube.com/playlist?list=PL2PY2-9rsgl2uKW0DB5FJ-YRCAG-JuSWN)