Vuelidate allows for validation to occur upon clicking a button, rather than waiting for the field

As I navigate my way through learning vuelidate, everything seems to be going smoothly, except for one thing. I can't figure out how to trigger validation only when the "Submit" button is clicked. Currently, the fields turn red as soon as I start typing, but I want them to wait until the user is ready to submit the form.

This is my progress so far:

Vue.use(window.vuelidate.default)
const { required, minLength, sameAs } = window.validators

new Vue({
el: "#app",
  data: {
  user: {
    login: '',
      password: '',
      repeatedPassword: ''
    }
  },
  validations: {
  user: {
    login: {
      required,
        minLength: minLength(5)
      },
      password: {
      required,
        minLength: minLength(8)
      },
      repeatedPassword: {
      required,
        sameAs: sameAs('password')
      }
    }
  }
})
input {
  border: 1px solid silver;
  border-radius: 4px;
  background: white;
  padding: 5px 10px;
}

.error {
  border-color: red;
  background: #FDD;
}

.error:focus {
  outline-color: #F99;
}

.valid {
  border-color: #5A5;
  background: #EFE;
}

.valid:focus {
  outline-color: #8E8;
}
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuelidate/dist/validators.min.js"></script>
<script src="https://unpkg.com/vuelidate/dist/vuelidate.min.js"></script>
`<div id="app">

  <input type="text" placeholder="login"
    v-model="user.login"
    v-on:input="$v.user.login.$touch"
    v-bind:class="{error: $v.user.login.$error, valid: $v.user.login.$dirty && !$v.user.login.$invalid}">
  <br/>    
  <input type="password" placeholder="password"
    v-model="user.password"
    v-on:input="$v.user.password.$touch"
    v-bind:class="{error: $v.user.password.$error, valid: $v.user.password.$dirty && !$v.user.password.$invalid}">
  <br/>  
  <input type="password" placeholder="repeat password"
    v-model="user.repeatedPassword"
    v-on:input="$v.user.repeatedPassword.$touch"
    v-bind:class="{error: $v.user.repeatedPassword.$error, valid: $v.user.repeatedPassword.$dirty && !$v.user.repeatedPassword.$invalid}"
  >
  <button :disabled="$v.user.$error" @click="$v.user.$touch()">
    Submit!
  </button>
</div>`

Answer №1

Adapting to the Vuelidate approach has been a bit challenging for me, but essentially, it operates in the following manner:

By setting it up this way, you can implement validation for individual form inputs/elements and then conduct an overall check to determine if the form is "dirty" and/or "invalid"

form: {
"name": {
"required": false,
"$invalid": true,
"$dirty": false,
"$error": false,
"$pending": false,
"$params": {
  "required": {
    "type": "required"
  }
}
},
"Age": {
  "required": false,
  "$invalid": true,
  "$dirty": false,
  "$error": false,
  "$pending": false,
  "$params": {
    "required": {
      "type": "required"
    }
  }
},
"$invalid": true, <------- This indicates whether the form is valid/invalid
"$dirty": false, <------- This reveals if the form has been interacted with.
"$error": false,  <-------  This assesses both invalidity and dirtiness
"$pending": false,
"$params": {
   "nestedA": null,
   "nestedB": null
}
}

In terms of practical application, one approach could involve triggering the validateform event upon submission.

@click.prevent="validateform"

Subsequently, create a validateform method within your Vue instance that verifies

$v.form.$invalid or $v.form.$error

and then either showcase errors or invoke the actual submit process.

Answer №2

After configuring the validations, all you need to do is invoke a method to validate any errors. Simply follow these steps:

<button @click="validate">Submit</button>

The validation method:

validate () {
  this.$v.$touch() // This will trigger validation for all fields
  if (!this.$v.$invalid) { // $invalid becomes true when validation fails
   // No validation errors found. Proceed with your desired action here
  }
}

Answer №3

Currently, the touched field turns red as soon as input is provided.

This indicates that the field is being marked as 'dirty' automatically, which was not the default behavior in the previous version (Vuelidate 2).

Please ensure that you do not have $autoDirty: true set or change it to "false."

In Vuelidate 2, all you need to do to achieve your desired outcome is to call $touch() on the submit click event, as $autoDirty defaults to false. Refer to Roland's answer for more details.

Answer №4

My approach to using VeeValidate 3 involves the following steps:

<validation-observer ref="jobValidation">
 <form>
     <button v-on:click="nextPage()" type="button">Next</button>
 </form>
</validation-observer>

Additionally, my implementation includes the following snippet within the methods:

nextPage(): void {                 
    const validation = (this.$refs.jobValidation as any);
    validation.validate().then(() => {
        if (validation.flags.invalid) {                           
            // Handling invalid inputs
            // Also displaying all errors in a summary
            validation.$children.forEach((child: any) => {
                child.errors.forEach((error: any) => {
                    console.log(error);
                });
                return;
            });
        } else {
            // Proceeding with valid data
            // Performing required actions
        }
    });  
},

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

Using CoffeeScript to Invoke Methods

I'm still learning CoffeeScript and encountering some challenges with calling methods. Can someone help me out? Here is the Card model I am working with: class exports.Card extends Backbone.Model defaults: pip: '4' suit: &apos ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

`switch tabs visibility based on checkbox selection`

There are 4 tabs available on a JSP page: Tab 1, Tab2, Tab3, and Tab4. Initially, only Tab1 is enabled, allowing users to freely work within that tab. However, Tabs 2, 3, and 4 are disabled, preventing users from accessing their contents. A checkbox is lo ...

jquery monitors an element to see if it contains a particular attribute, then takes action accordingly

I'm attempting to conceal a div when an anchor tag (a) has a particular href, and reveal it when the href is different. This is what I've tried: if($('a[href="#intro"]').not(".active")) { $('.navbar-brand').hide();} else ...

Tips for saving data in the $localStorage as an object

I need to store all the items in $localStorage like this: $localStorage.userData.currentUser = data.name; $localStorage.userData.devId= data.id; $localStorage.userData.userRole = data.roles[0].name; $localStorage.userData.userId = data.user_id; Here is t ...

Utilizing express and socket.io for seamless cross-domain communication

Is there a way to activate cross-domain functionality for express.io? I require it for a Cordova application, but when using Chrome, I get an error message saying "No 'Access-Control-Allow-Origin' header is present on the requested resource. Orig ...

Angular controller utilizing the `focusin` and `focusout` events from jQuery

Can anyone help me figure out why this piece of code is generating syntax errors in my AngularJS controller? $(".editRecur").focusin(function() { $(.recurBox).addClass("focus"); }).focusout(function() { $(.recurBox).removeClass("focus"); }); ...

Guide on transferring input element to h3 tag without using the URL

Is there a way to update the h3 tag every time a user clicks without updating the tab URL? I only want to update the h3 tag. I have attached all files and a screenshot of the URL. <!DOCTYPE html> <html> <head> </head> ...

Centering text in a D3 donut chart

Struggling with centering text inside a d3 donut chart for a project. While trying to modify a piece of code, I find myself lost in the complexity of it. Despite my efforts, the text added to the center is not perfectly centered. I have attempted various ...

Develop a seamless user experience by creating dynamic forms using Jquery, PHP, and

I have been attempting to create a simple contact form using jQuery, AJAX, and PHP without refreshing the page. Everything seems to be working smoothly except for event.preventDefault(); Here are my files: Contact_engine.php <?php $name = $_POST ...

Utilizing Color with Nuxt and Vuetify: Enhancing Components such as v-toolbar

Hello, I need help with my Nuxt 2 and Vuetify 2 project. I want to customize a simple Vuetify v-toolbar component by giving it a specific color. The official documentation suggests using the following code: <template> <v-toolbar flat color=&q ...

Error Message: Unexpected Type Error with axios in Vue 3

Trying to implement axios in my Vue3 project for fetching APIs. Here is the code snippet from my component: export default { name: "Step2", data() { return { loading: true; }; }, mounted() { this.loading = false; }, ...

The function assigned to [variable].onclick is not being executed, despite no errors being displayed in the console

I'm new to javascript and I'm looking for help with a simple task. I want to create a code that when clicking on an image, it will open in a modal. This feature is important for viewing full-size images on my portfolio. Although there are no erro ...

Preventing React setState from replacing the entire object

When attempting to update a customer's age using setState, the object is altered before calling setState, but the existing object is not updated. customerOnChange(event, field) { //Customer's age currently set at 80 var customer = { ...t ...

Receiving AssertionError when running unit tests in Vuex comparing to { Object (type, text) }

I've been struggling with unit testing Vuex actions recently, finding it difficult to understand what the tests are actually expecting. I'm following the guidelines on https://vuex.vuejs.org/en/testing.html and using their action helper function. ...

Issue with Vue.js v-show functionality not triggering properly following an axios request

I am facing an issue where v-show is not behaving as expected. I suspect this is because this.conversation.hidden is not initially set when the browser is rendered due to it being loaded asynchronously. How can I resolve this issue? Thank you in advance! ...

Control the value dynamically with Powerange using JavaScript

I have incorporated the Powerange library into my form for creating iOS style range bars. This javascript library offers a variety of options provided by the author. Is there a method to programmatically move the slider to a specific value using JavaScrip ...

What is the best way to showcase a collapsible tree using AngularJS and Bootstrap?

I'm currently working on a web application that requires the display of a tree structure using lists. Here is the basic outline: * Node 1 * Node 1.1 * Node 1.1.1 * Node 1.1.1.1 * Node 1.1.2 * Node 1.2 http://jsfid ...

How to pass an array as parameters in an Angular HTTP GET request to an API

Hey there! I'm relatively new to Angular and I've hit a roadblock. I need to send an array as parameters to a backend API, which specifically expects an array of strings. const params = new HttpParams(); const depKey = ['deploymentInprogre ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...