Error in Vue Vuelidate appearing when form is submitted with empty data property

I have been working on some basic validation for required fields and minimum length. The problem arises when I submit a network request for data insertion, the validation works perfectly fine. However, after the network call, if I try to make my text field empty, it shows an error. How can I ignore this validation? Below is the code snippet of my component. Thank you in advance.

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-6">
                <form @submit.prevent="processTaskForm">
                    <div class="card my-3">
                        <div class="card-header">
                            <h3 class="text-center">Add Task in Todo</h3>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label for="">Task</label>
                                <input type="text" class="form-control" name="task" v-model.trim="$v.task.$model" id="task">
                                <div v-if="$v.task.$error">
                                    <div  v-if="!$v.task.required" class="text-danger">
                                        Field is required
                                    </div>
                                    <div  v-if="!$v.task.minLength" class="text-danger">
                                        Task must be minimun length of 8
                                    </div>
                                </div>
                            </div>
                            <input type="submit" value="Add Task" class="btn btn-primary">
                            <!-- <span v-if="submitStatus === 'ERROR'" class="text-danger ml-3">Please fill all fields correctly</span> -->
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>
<script>
    import axios from 'axios'
    import {required,minLength} from 'vuelidate/lib/validators'
        export default {
            name: "Todo",
            data() {
            return {
                task :'',
                submitStatus : 'OK'
            }
        },
        validations: {
            task: {
                required,
                minLength: minLength(8)
            }
        },
        methods:{
            processTaskForm(){
                this.$v.$touch()
                if (this.$v.$invalid) {
                    this.submitStatus = 'ERROR'
                } else {
                    this.submitStatus = 'PENDING'
                    const headers = {
                        "Authorization" : "Bearer "+this.$store.state.user.token
                    }
                    axios.post('/api/add-task', {
                        task: this.task,
                    },{
                        headers:headers
                    })
                    .then((response) => {
                        if(response.data.status){
                            this.task = ""
                            this.submitStatus = 'OK'
                        }
                    }, (error) => {
                        console.log(error);
                    });
                }
            }
        }
    }
</script>

<style>

</style>

Answer №1

When you clear the task field, it is important to immediately invoke the this.$v.$reset() method. This action will effectively reset the $dirty flag for both the model and all its nested children back to false.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React.js router - struggles to clean up unsightly query parameters in the URL

I've been trying to eliminate the query string by following this solution: var { Router, Route, IndexRoute, IndexLink, Link } = ReactRouter; var createHashHistory = History.createHashHistory; var history = createHashHistory({queryKey: false} ...

Incorporate a dynamic avatar into your Navbar with the help of Bootstrap-Vue

I have integrated the Navbar component with Boostrap-Vue and am trying to include an avatar, where the image comes from a variable in the application. The issue I am facing is that I am unable to bind the variable to the avatar component within a slot, as ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

Differences Between Data Captured from Form Submissions and Data Obtained Through Ajax

When attempting to incorporate reCAPTCHA into my MVC site, I encountered an issue where it would not validate unless submitted from a form. Here is the current implementation: @using(Html.BeginForm("VerifyCaptcha", "Signup") ) { @ReCaptch ...

Angular- Product Details

I'm currently expanding my knowledge of angular (utilizing the ionic framework with phone gap included) and I'm working on developing a single application that displays a list of data. When a user clicks on an item in the list, I want to show the ...

Ways to boost memory capacity in nodejs

I've been attempting to increase the memory limit in node.js, and to do so I added an environment variable. You can see how I did it here Unfortunately, it doesn't seem to be working as expected. I even tried using capital letters with no succe ...

What is the best way to utilize a variable in jQuery outside of a function?

I am attempting to utilize the .index method to determine the position of the image that is clicked on. I then need to use that number in another variable which must be external to the function. var index; $('.product img').click(function () ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (http://www.highcharts.com/stock/demo/lazy-loading). I attempted to i ...

Handling typeError in Vue.js JavaScript filter for object manipulation

I need to sort an object based on state names (e.g. Berlin, Bayern ...). Below is the API response I received. "states":{ "Bayern":{ "total":13124737, "rs":"09", "va ...

Encountering a problem with AngularJS ui router templates

I have defined the following routes in my project: $stateProvider .state('access', { abstract: true, url: '/access', templateUrl: 'login.html' }) .state('access.signin', { ...

Error: Vue Loader Unable to find module '@'

Software Version 15.4.0 Link to Reproduction Example https://codepen.io/fendi-tri-cahyono/pen/wbXKMZ?editors=0010 Steps to Recreate the Issue ERROR in ./node_modules/vue-extend-layout/vue-extend-layout.vue?vue&type=script&lang=js& (./node_ ...

"Improving Response Time in Vue and Enhancing UI with Vue Material

I have integrated VueJs 2.0 with Vue Material. In the application, I am displaying a table with numerous rows containing multiple input fields and select fields (VueMaterial components). During data entry in the input fields, the components tend to slow d ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Converting sections of JSON data into boolean values

Is there a way to convert certain parts of a JSON string into booleans? Here is an example of my JSON string: { "file_id": { "width": "560", "height": "270", "esc_button": "1", "overlay_close": "1", "overl ...

Looking to encode/decode a JSON response in order to transfer it to a different webpage

Currently, I have a website application where I am required to pass a JSON response (in string format) across the site. To achieve this, I have been using a hidden type value and passing it upon the submission of a link/button which subsequently triggers a ...

What is the best way to animate the preprending of a div in an AJAX response?

Here is the code I am currently working with: $.ajax({ type: 'POST', url: 'load_more.php', data: {val:myval}, success: function (data) { $("#load_current").prepend(data); ...

Why am I encountering an issue while trying to access req.user.id?

Having set up passport authentication on my express, node project, I encountered an error when trying to access req.user. The error message displayed is Property 'id' does not exist on type 'User'.ts(2339). Below is the relevant code sn ...

Unable to display socket data in Angular js Table using ng-repeat

div(ng-controller="dashController") nav.navbar.navbar-expand-sm.navbar-dark.fixed-top .container img(src='../images/Dashboard.png', alt='logo', width='180px') ul.navbar-nav li.nav-item ...

Issue: Unable to reach essential Node.js modules

After attempting to deploy Next.js on Cloudflare Pages, I encountered the following error: Error: Could not access built-in Node.js modules. It is recommended to ensure that your Cloudflare Pages project has the 'nodejs_compat' compatibility flag ...