The easiest way to add native form validation in Vue.js. β
Vaibhav Khulbe
Posted on August 14, 2020
Now, this statement might be bold but this is what I found out to be the easiest way possible to add some validations natively. Though there are many libraries like FormValidation and Vuelidate, one of the simpler way to check the input elements (and others) is to go the native way which is built into Vue.
Ready to add some checks? Let's get this real quick!
What's in the form? π
Let's take the simplest of the lot. There are two input fields, one drop-down and one submit button. It doesn't look pretty, and remember, we're here to do the validation.
Here are the different states of our form:
The default state
The filled state
The error(s) state
If one of the required fields is not filled...
If you try to submit without your name/review/ratings...
Code it! π¨βπ»
I hope you're good with the HTML and CSS part of the form. If not, you can see the code in the embed towards the end of this article.
The product-review
component takes in the following HTML as a template
:
<form class="form" @submit.prevent="onSubmit">
<p>
<label for="name">Name:</label>
<input id="name" v-model="name">
</p>
<p>
<label for="review">Review:</label>
<textarea id="review" v-model="review"></textarea>
</p>
<p>
<label for="rating">Rating:</label>
<select id="rating" v-model.number="rating">
<option>βββββ</option>
<option>ββββ</option>
<option>βββ</option>
<option>ββ</option>
<option>β</option>
</select>
</p>
<p>
<input type="submit" value="Submit">
</p>
</form>
As you can see, it's a pretty straightforward code having the @submit.prevent
event modifier attached to the onSubmit
method which we will define later.
We're using the v-model
directive on the name
input, review
text field, and the rating
selector to give us two-way data-binding.
Add custom validation
Let's first create the onSubmit
method. Here, we make the productReview
object which refers to the name
, review
and rating
which should've been initialised inside the data()
object as null
.
onSubmit() {
let productReview = {
name: this.name,
review: this.review,
rating: this.rating
}
this.name = null
this.review = null
this.rating = null
}
To collect the errors, we'll make an empty errors
array in our data object of Vue instance.
Next, we use good old if-else
in JavaScript to check if there is some data entered in these three fields or not. Hence, we wrap our productReview
object inside the if
as:
if(this.name && this.review && this.rating) {
let productReview = {
name: this.name,
review: this.review,
rating: this.rating
}
this.name = null
this.review = null
this.rating = null
}
Now, if these values are not filled in, we add the else
block and check if there is not a name
, rating
or a review
, then simply push()
this into our initially empty errors
array with the error message we want to display inside the push()
function's argument as a String.
else {
if(!this.name) this.errors.push("Name required.")
if(!this.review) this.errors.push("Review required.")
if(!this.rating) this.errors.push("Rating required.")
}
Display those errors
Inside of our template, we add a new <p>
tag before the name input field. Using Vue's v-if
directive, we'll check if errors array has some length
. This means when errors
is not empty (i.e it has some errors), we add a <b>
which says "Please correct the following error(s):"
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
For a single of multiple errors, we'll display it in an unordered list. Therefore, for each <li>
, we use the v-for
directive to iterate through the array to print each of the error
.
And there you have it! Try submitting the form by leaving on or two (or if you don't even have a name, leave them all! οΌοΏ£οΈΆοΏ£οΌβ). The form should send the error message(s). π₯³
If you're stuck somewhere in the code or just want to see the output, I've embedded the Pen below:
Where to next? π€
While this was a super simple beginner-friendly approach towards form validation in Vue, your app may be much more complex or big. For that you can try out the following resources:
- Vue.js official Cookbook example.
- Validation with VeeValidate.
- Vuelidate examples.
Thanks for reading, I appreciate it! Have a good day. (βΏββΏββΏ)
π₯΅π₯Άπ₯΅π₯Ά
β Microsoft Developer UK (@msdevUK) August 11, 2020
If you're unsure what a bool is, this will explain: https://t.co/4hjKJtxYNE
Image source: https://t.co/2mBLe57X92#DevHumour #Programming pic.twitter.com/WVoBkIxLtT
π« Subscribe to my weekly developer newsletter π«
PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, here's my Medium profile.
Posted on August 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.