Validating a simple form using Vue 3

/ #Vue.js


Often you want to validate a form before you send data to the backend. Here is a short guide on how to do this using Vue.

The form

<div id="validate-form-app">
    <form method="post" action="." @submit="validateForm">
        <label>Title</label>
        <input type="text" name="title" class="input" v-model="title">

        <button class="button">Submit</button>
    </form>
</div>

Here we have a simple form with a text input field. We want to use Vue to check if this field is filled or not. Inside the form tag, we use Vue to call a method called "validateForm" when we submit the form.

<script>
    const validateFormApp = {
        data() {
            return {
                title: ''
            }
        },
        methods: {
            validateForm(e) {
                if (this.title) {
                    return true
                } else {
                    alert('Form error')

                    e.preventDefault()

                    return false
                }
            }
        }
    }

    Vue.createApp(validateFormApp).mount('#validate-form-app')
</script>

First we create a new Vue app for the validation. We have a simple data array with the title. This could be expanded to all fields you need.

Inside the methods object, we have a method called "validateForm". As you can see, we get a parameter called "e". This is short for "event".

We do a check on the title, if this is not empty, we return true and the form will be submitted. If it's empty, we show a simple error alert to the user and prevent the form from submitting.

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.