Vue.js Functions

 

Form Handling in Vue.js: A Comprehensive Guide to Validation and Robust Input Processing

Vue.js, a lightweight yet powerful JavaScript framework, is a preferred choice for building interactive user interfaces. Given its sophistication, many businesses are looking to hire Vue.js developers to harness its full potential. One of the most common tasks these developers undertake in web development is handling forms and validating the user’s input. In this blog post, we will focus on why hiring Vue.js developers can bring value to your projects, particularly for creating robust input handling, with detailed Vue.js examples to illustrate the points.

Form Handling in Vue.js: A Comprehensive Guide to Validation and Robust Input Processing

Creating a Basic Vue.js Form

Before we dive into validation, let’s first look at a simple Vue.js form. Suppose we want to create a form to capture a user’s name and email. The Vue.js component might look like this:

```js
<template>
    <form @submit.prevent="submitForm">
        <input v-model="name" placeholder="Name" />
        <input v-model="email" placeholder="Email" />
        <button type="submit">Submit</button>
    </form>
</template>

<script>
export default {
    data() {
        return {
            name: '',
            email: ''
        }
    },
    methods: {
        submitForm() {
            console.log('Name:', this.name);
            console.log('Email:', this.email);
        }
    }
}
</script>
```

Here we’ve used the `v-model` directive to create two-way data bindings for our form inputs. This means that whenever the user changes the input fields, the `name` and `email` data properties will be automatically updated.

The `@submit.prevent=”submitForm”` is listening for the submit event and calling our `submitForm` method. The `.prevent` modifier is a Vue.js shortcut to stop the form from doing the default form submission.

Adding Validation to Vue.js Forms

Now that we have a basic form, let’s add some validation to ensure the user has filled out all fields and provided a valid email.

First, we’ll add some additional data properties to keep track of the validation state:

```js
data() {
    return {
        name: '',
        email: '',
        nameValid: false,
        emailValid: false
    }
}
```

Next, we can add some computed properties that will determine if the name and email are valid:

```js
computed: {
    isNameValid() {
        return this.name.length > 0;
    },
    isEmailValid() {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email);
    }
}
```

These computed properties will automatically update whenever their dependencies (`name` and `email`) change.

Finally, we can modify our `submitForm` method to check the validation state before submitting:

```js
methods: {
    submitForm() {
        this.nameValid = this.isNameValid;
        this.emailValid = this.isEmailValid;
        
        if (this.nameValid && this.emailValid) {
            console.log('Name:', this.name);
            console.log('Email:', this.email);
        } else {
            console.log('Form is not valid.');
        }
    }
}
```

Providing Validation Feedback to the User

Now that we have validation working, we can provide some visual feedback to the user when they enter invalid data. We can add some conditional classes to our input fields that will add a red border when the input is invalid:

```html
<input 
    v-model="name" 
    placeholder="Name" 
    :class="{ 'is-invalid': !nameValid && name.length }"
/>

<input 
    v-model="email" 
    placeholder="Email" 
    :class="{ 'is-invalid': !emailValid && email.length }"
/>
```

In the above code, the ‘is-invalid’ class is added to the input when the corresponding data property is not valid and it is not empty. This avoids marking

the fields as invalid before the user has had a chance to enter anything.

We’ll need some CSS to give the ‘is-invalid’ class a red border:

```css
.is-invalid {
    border: 1px solid red;
}
```

To take the user feedback further, we can add error messages under the input fields:

```html
<div class="error" v-if="!nameValid && name.length">Please enter a name.</div>
<div class="error" v-if="!emailValid && email.length">Please enter a valid email.</div>
```

And some CSS to style the error messages:

```css
.error {
    color: red;
    margin-top: 5px;
}
```

Using a Vue.js Form Validation Library

While it’s useful to know how to roll your own validation, in a large application it can become tedious to manually handle the validation state for every field. This is precisely where you can benefit from the expertise of professionals when you hire Vue.js developers. With their knowledge and experience, they can efficiently use a Vue.js form validation library, such as Vuelidate or VeeValidate. Hiring Vue.js developers can streamline your validation processes, adding value to your application development.

Here’s an example of how we might use Vuelidate to handle the validation for our form:

```js
<template>
    <form @submit.prevent="submitForm">
        <input v-model="name" placeholder="Name" />
        <div v-if="!$v.name.required">Name is required.</div>
        
        <input v-model="email" placeholder="Email" />
        <div v-if="!$v.email.required">Email is required.</div>
        <div v-if="!$v.email.email">Email must be valid.</div>

        <button type="submit">Submit</button>
    </form>
</template>

<script>
import { required, email } from 'vuelidate/lib/validators'

export default {
    data() {
        return {
            name: '',
            email: ''
        }
    },
    validations: {
        name: {
            required
        },
        email: {
            required,
            email
        }
    },
    methods: {
        submitForm() {
            this.$v.$touch();
            
            if (this.$v.$invalid) {
                console.log('Form is not valid.');
                return;
            }
            
            console.log('Name:', this.name);
            console.log('Email:', this.email);
        }
    }
}
</script>
```

Vuelidate provides a `$v` object that we can use to check the validation state of our fields. In the `submitForm` method, we use the `$touch` method to mark all fields as touched, which will trigger the error messages to show if the fields are invalid.

Conclusion

Form handling and validation is a crucial part of any web application. Vue.js, with its reactive data model and extensive ecosystem, makes it easy to build robust and user-friendly forms. This is one of the key reasons why many businesses decide to hire Vue.js developers.

Whether you choose to roll your own validation, a task Vue.js developers excel at, or use a library like Vuelidate, the principles are the same. Always validate your data and provide clear feedback to the user. By hiring Vue.js developers and adopting these principles, you’re well on your way to creating a great user experience with Vue.js forms.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Talented Fullstack Developer with 5+ years of Vue.js experience. Expertise in smart contracts, RESTful APIs, GraphQL, AWS, and CI/CD.