Form validation, also known as form field validation, ensures that a user fills out all required fields in a web form. If a field has an invalid value, it will display an error message and prevent form submission until the values satisfy all the rules.
Template-driven validation is a type of form validation where validation rules are set directly in the form elements using directives.
To implement template-driven validations in Vue.js, we can use VeeValidate. VeeValidate is a plugin for Vue.js that allows you to validate input fields and display errors.
Here is an animated image of what you will build in this tutorial:
At the end of this tutorial, you will have a registration form that uses VeeValidate to validate the input fields.
This tutorial assumes knowledge of JavaScript strings and objects. Some familiarity with Vue will be beneficial but is not required. To learn more about Javascript, check out the How To Code in Javascript series.
We will focus on building a single local HTML file with references to various cloud-hosted libraries. It is possible to use @vue/cli
to create a Vue project and use a package manager to install vee-validate
; however, that approach is outside of this tutorial’s scope.
You will need the Vue.js framework and the VeeValidate library.
First, use your terminal to create a new file called register.html
:
And add some initial code for a webpage:
A browser build for Vue.js is available via cdnjs
. A browser build for VeeValidate is available via jsdelivr
. Add both to the <body>
of the register.html
file:
These files are provided by CDNs (content delivery networks). There is nothing to download or save locally.
You now have a webpage ready to use the latest stable versions (as of this writing) of Vue.js and VeeValidate.
To establish some styling, you can use Bootstrap. To add some iconography, you can also utilize Font Awesome.
Browser builds for Bootstrap and Font Awesome are available via BootstrapCDN
. Add both to the <head>
of the register.html
file:
At this point, you have Vue, VeeValidate, Bootstrap, and Font Awesome. Next, you will create the form to validate.
This example form will seek five pieces of information from the user. You will need a name
, email
, username
, password
, and password_confirmation
.
First, add some initial markup for the form to the <body>
of the register.html
file before the <script>
tags:
This code establishes an empty <form>
and uses some Bootstrap utilities for layout and appearance.
Next, add the form fields to the <form>
. Start with the field for name
:
This code creates a <label>
for name
, a Font Awesome icon for fa-user
, and an <input>
for name
.
You can make similar additions to the <form>
for the other pieces of information—email
, username
, password
, and password_confirmation
:
This code creates <label>
s, a Font Awesome icons, and <input>
s. Each input has a unique id
and name
.
Add a button for registration to complete the <form>
:
This code creates a large submit button using Bootstrap styles.
You can open register.html
in a web browser to check the progress of the app.
Next, you will create a Vue instance and mount it to the #signup-form
.
Add a new <script>
tag at the end of the <body>
and define signupForm
:
Add properties to the data
object:
Then, reference the properties with v-model
in each of the fields.
For the name
field, add the following:
For the email
field, add the following:
For the username
field, add the following:
For the password
field, add the following:
Finally, for the password_confirmation
field, add the following:
At this point, you have a Vue instance with models for name
, email
, username
, password
, and password_confirmation
.
ValidationObserver
and ValdiationProvider
Next, you will need to register ValidationObserver
and ValidationProvider
.
You can add both to a new <script>
tag at then end of the <body>
:
Now, you can use <validation-observer>
to wrap the entire <form>
. And you can use <validation-provider>
to wrap the fields:
You now have a form prepared with <validation-observer>
and <valdiation-provider>
.
A VeeValidate rule sets limits or conditions on what can be entered in one or more fields. Validation rules are checked when you update a record containing fields requiring validation. If the rule is violated, a trappable error occurs.
For example, you can use the required
validator:
You can pass multiple validations separated by a pipe character (|
).
For example, you can use the required
and the email
validators:
Alternatively, you can pass an object for more flexibility:
Now every time the input changes, the validator will run the list of validations from left to right, populating the errors helper object whenever an input fails validation.
As at the time of writing this tutorial, VeeValidate has 30 rules for form validation with an option of creating your own rules.
Next, you need to import the VeeValidateRules
.
You can add it to a new <script>
tag at then end of the <body>
of in the register.html
file:
Then, you can loop over the rules to make them all available:
And apply required
rules for all the inputs:
For email
, you will also apply a rule for valid email addresses:
For password
you will also apply a rule for a minimum length of 6
characters:
Now, you have required
, email
, and min
rules for the fields.
For password_confirmation
you will need to match the value of password
to be valid. To accomplish this, you will rely on ValidationObserver
, which allows password_confirmation
to be aware of password
.
Add the vid
to the password
field, so password_confirmed
has a target:
Add the confirmed
rule to the password_confirmation
field, so password_confirmed
compares its value against the value for password
:
Now, you have required
, email
, min
, and confirmed
rules for the fields.
VeeValidate allows you to write custom validation rules and messages with extend
and validate
.
Add a rule that prevents users from registering with some restricted words. In this example, you will restrict users from using the words admin
, password
, and administrator
:
Add the custom rule to the username
field:
Now, you have required
, email
, min
, confirmed
, and checkuser
rules for the fields. The rules are all established, and now you can start displaying error messages.
VeeValidate has errors
available. VeeValidate also has multiple flags for state information. You can access these using Vue’s v-slot
.
You will also use Vue’s v-show
to display the VeeValidate error messages and use Bootstrap’s invalid-feedback
class for styling the errors.
Additionally, you will use VeeValidate flags for dirty
, valid
, and invalid
in combination with Vue’s v-bind:class
and Bootstrap’s is-valid
and is-invalid
classes for styling the fields:
At this point, you have access to dirty
, valid
, invalid
, and errors
. You added logic to display error messages as feedback under the associated field. If the field is interacted with and invalid, it will apply Bootstrap’s is-invalid
class. If the field is interacted with and valid, it will apply Bootstrap’s is-valid
class.
In the next step, you will handle submitting the form.
VeeValidate also provides an invalid
flag for ValidationObserver
and a handleSubmit
function. You can access these using Vue’s v-slot
:
Use Vue’s event modifiers to capture form submission with @submit.prevent
. You will also use VeeValidate’s handleSubmit
to prevent form submission until all fields are valid:
This will call onSubmit
which can be defined as a console.log
message:
Keep the <button>
in a disabled
state so it will not submit information while any fields are invalid
:
At this point, you can open register.html
in a web browser and interact with the form to test the validations.
In this tutorial, you have demonstrated how to validate form inputs using the template-driven approach. VeeValidate has allowed you to validate form inputs with existing rules, extend new rules, display errors, and handle the form submission.
If you’d like to learn more about Vue.js, check out our Vue.js topic page for exercises and programming projects.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!