Vuelidate is failing to display the accurate error messages

Exploring vuelidate for the first time has been an interesting journey. I found that while following some of the tutorial examples in their documentation, my code was showing errors even before I started typing. Strangely, the error messages were not accurate, with a "minlength" related error appearing before the expected "required field" message.

You can check out the vuelidate documentation here, which I was referencing. Additionally, here is the official Vue Material form example that I was looking at: link.

When I tried to mimic the official vuelidate example, the error message would display right away instead of waiting for me to input something:

https://i.sstatic.net/kasXD.png

Below is the single field form that I was attempting to implement the validation on:

<template>
    <div class="action">
        <div class="md-layout md-gutter md-alignment-bottom-center ">
            <form novalidate class="md-layout" @submit.prevent="validateUser">
                <md-card class="cardStyle" >
                    <md-card-header>
                        <div class="md-title">FORM TEST</div>
                    </md-card-header>

                    <md-card-content>
                        FORM TYPE

                        <md-card class="md-medium-size-25 md-small-size-60 md-xsmall-size-100">
                            <md-card-expand>
                                <md-card-actions md-alignment="space-between">
                                    <div>
                                        INFO
                                    </div>

                                    <md-card-expand-trigger>
                                        <md-button class="md-icon-button">
                                            <md-icon>keyboard_arrow_down</md-icon>
                                        </md-button>
                                    </md-card-expand-trigger>
                                </md-card-actions>

                                <md-card-expand-content>
                                    <md-card-content>
                                        <md-field>
                                            <div>
                                                <label for="eventType">Event name</label>
                                                <md-input name="eventName" id="eventName" v-model="form.eventName"/>
                                            </div>
                                        </md-field>
                                            <span class="md-error" v-if="!$v.form.eventName.required">REQUIRED</span>
                                            <span class="md-error" v-else-if="!$v.form.eventName.minlength">INVALID</span>

                                    </md-card-content>
                                </md-card-expand-content>
                            </md-card-expand>
                        </md-card>
                    </md-card-content>
                </md-card>
            </form>
        </div>
    </div>
</template>

<style  scoped>
    /*.cardStyle {
        min-width: 50%;
        margin: 4px;
        display: inline-block;
        vertical-align: top;
    }*/
    .action {
        display: flex;
        align-items: center;
        justify-content: center;
        position:sticky;
        padding-top: 5%;
        padding-bottom: 5%;
    }
</style>

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

    export default {
        name: 'Budget',
        mixins: [validationMixin],
        data: () => ({
            form: {
                formType: null,
                eventName: null,
                BU: null,
                startDate: null,
                startHour: null,
                endDate: null,
                endHour: null,
                participants: null,
                coverage: null,
                local: null,

              },
        }),
        validations: {
          form: {
            eventName: {
              required,
              minLength: minLength(3)
            },
            lastName: {
              required,
              minLength: minLength(3)
            },
            age: {
              required,
              maxLength: maxLength(3)
            },
            gender: {
              required
            },
            email: {
              required,
              email
            }
          }
        },

    }
</script>

Answer №1

It is important to address validation errors right from the start, as mentioned. One approach to overcome this challenge is by utilizing the lazy attribute on your v-model and employing the $v object as your model in the following manner:

<md-input name="eventName" id="eventName" v-model.lazy="$v.form.event.Name.$model"/>

Furthermore, it is advisable to manually check for errors and display corresponding messages if errors are present:

data() {
  return {
    hasError: false,
  };
},
methods: {
 submit() {
   if (this.$v.form.$pending || this.$v.form.$error) {
      this.hasError = true;
   }
 }
},
.....

When presenting errors, you can now conduct several validations:

<span class="md-error" v-if="hasErrors && !$v.form.eventName.required">REQUIRED</span>

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

Vue.js - Using Filters to Filter Data from Multiple Fields

I'm currently working on filtering a nested array inside an array of objects in Vue.js. Below is a code snippet from the component: filteredProducts: function() { if (!this.filters.appointments.length && !this.filters.powers.length && !this.filters. ...

When it comes to TypeScript, there is a limitation in assigning a value to an object key with type narrowing through the

I created a function called `hasOwnProperty` with type narrowing: function hasOwnProperty< Obj extends Record<string, any>, Prop extends PropertyKey, >( obj: Obj, prop: Prop, ): obj is Obj & Record<Prop, any> { return Object ...

Click-triggered CSS animations

Trying to achieve an effect with regular JS (not jQuery) by making images shake after they are clicked, but running into issues. HTML: <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"... JS: function wrongAnswer(){ docume ...

What benefits does minifying server-side nodejs code provide?

Is there a benefit to minifying Node.js code in the same way as minifying JavaScript, particularly for reducing size and improving network download speed? When a file is required in Node.js, it is loaded into V8 and processed and stored in memory in some f ...

The drop-down component is being filled with data but unfortunately, only dummy data is functional at the

Having trouble populating data in the drop-down component. Everything works fine when using dummy JSON data as shown in the comments. The GET request service retrieves the necessary data, and then I assign the response to the appropriate variable. The GET ...

Implementing the jQuery datepicker in Angular.js can be challenging

I recently started learning Angular.js and have been working on a web application using this framework. I am now looking to include a datepicker in one of my forms. Below is the code snippet that I have implemented: app.js myapp.directive(& ...

What is the best way to use ajax to append a value to an input if it is empty, or add a comma with

I recently came across this answer and implemented the following code: Here is the Ajax receiver: success: function(data) { jQuery("#assigncat").val(function(i,val) { return val + (val ? '' : ', ') + data.cat_id; ...

The ngHide directive is only functional when used in conjunction with the ngRoute module, but unfortunately

Upon logging into my app, I want the login and signup buttons to disappear from the navigation bar. To achieve this, I am utilizing the ng-hide directive. This directive is triggered when the login is successful and a token is received from the server, whi ...

Symfony2 requires clarification and direction when it comes to managing quantities in a shopping cart

My current challenge involves managing quantities in a shopping cart. I can easily add, delete, and view products in the cart, but am struggling with increasing or decreasing quantities if a user wants to purchase multiple units of the same product. BACKG ...

When req.body is instantiated, Mongoose returns an empty object

Hello there! Invoice model contains a nested Item array, and I am creating a new Item object using the data from newItem.ejs. However, Mongoose is returning an empty object even though the request body is not empty. I would greatly appreciate any advice ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

Integrate third-party code into your Angular application

I've been working on an Angular project and I wanted to spice things up by adding a confetti animation. I found this cool animation that I'd like to incorporate into my project: http://jsfiddle.net/vxP5q/61/?utm_source=website&utm_medium=emb ...

The Redux Toolkit Slice Reducer fails to function properly when incorporating an extra Reducer that is not compatible

I am relatively new to the world of Redux and have been attempting to use RTK right from the start. It has been quite a challenging and confusing experience for me so far. Recently, I decided to include a standard Reducer instead of an extraReducer in my ...

Trigger an Alfresco update action by adding content through a link

My current setup involves utilizing Alfresco Community Edition 4.0.e. I have set up Inbound and update rules on a specific folder. During the rule invocation process, my Java script is executed followed by calling my webservice. However, I am encounterin ...

The input value remains a string even after it has been converted to a float

I can't figure out where I'm going wrong. I'm attempting a simple task: getting user input, converting it to a float, and performing a calculation with that value. However, all I keep getting is NaN. Here's the input (I normally replac ...

The useTransition() method in React remains stuck in the isPending state when making API calls from routes in the /pages/api directory

I'm encountering an issue with the useTransition() function where it remains true and never changes back to false. I am attempting to delete a record from MongoDB and after completion, I want to refresh the React Server Component following the guideli ...

What is the best way to integrate Express JS with Google Charts?

I'm currently working on an Express application and I need to integrate Google charts into it. I found this helpful article here for guidance. Additionally, I would like to know how to replace manual data with data from a MySQL database. ...

What is the method to append text in Vue.js upon clicking?

My Vue Material (Vue.js) tag has a function: <md-button id="" v-on:click.native="requestSelected(request)"> methods: { requestSelected: function(request) { request.accepted = true; console.log(request); ...

Utilize JavaScript or jQuery to align a list item center on a horizontal scrolling navigation bar

Currently, I am utilizing bootstrap 4.6 for a webpage, and while the default navbar doesn't meet my requirements for mobile navigation, I am attempting to customize it to function like MODE_SCROLLABLE in Android. Therefore, I need it to activate the l ...

How can I rectify the varying vulnerabilities that arise from npm installation?

After running npm audit, I encountered an error related to Uncontrolled Resource Consumption in firebase. Is there a solution available? The issue can be fixed using `npm audit fix --force`. This will install <a href="/cdn-cgi/l/email-protection" clas ...