Why is my custom Vuelidate validator not receiving the value from the component where it is being called?

On my registration page, I implemented a custom validator to ensure that the password meets specific criteria such as being at least 12 characters long and containing at least one digit.

However, I encountered an issue where the custom validator was not receiving the input value when triggered, resulting in undefined values being shown in the console. To troubleshoot, I used mustache code to verify that the input data was indeed being transferred to the variable successfully.

You can find the validator code below:

import {  minLength, helpers } from '@vuelidate/validators'; // imports are working fine


const passwordValidators = {
    minLength: minLength(12),
    containsUppercase: helpers.withMessage(
        () => 'Password does not contain any Uppercase characters (A-Z)',
        function(value: string): boolean {
            console.log(value); // value is undefined
            return /[A-Z]/.test(value);
        }
    ),
    containsLowercase: helpers.withMessage(
        () => 'Password does not contain any lowercase characters (a-z)',
        function(value: string): boolean {
            console.log(value); // value is undefined
            return /[a-z]/.test(value);
        }
    ),
    containsNumber: helpers.withMessage(
        () => 'Password does not contain any digit characters (0-9)',
        function(value: string): boolean {
            console.log(value); // value is undefined
            return /[0-9]/.test(value);
        }
    )
}
export default passwordValidators

Here's how it is incorporated into a vue.js component:

//somewhere up 
import passwordValidators from '@/validators/password-requirements';
import { required, email, sameAs } from '@vuelidate/validators';
//inside defineComponent
validations() {
            return {
                email: { required, email },
                password: {
                    required,
                    passwordValidators
                },
                firstName: { required },
                lastName: { required },
                confirmPassword: { required, sameAsPassword: sameAs(this.password) }
            }
        },

The versions of the libraries used are:

  • "@vuelidate/core": "^2.0.0-alpha.34",
  • "@vuelidate/validators": "^2.0.0-alpha.26",

Answer №1

The key to solving the problem was quite simple: taking the time to carefully read and understand the documentation. As per the documentation: "Suppose you want a validator that checks if a string contains the word cool in it. You can write a plain JavaScript function to check that:"

Validators are essentially functions that are passed to objects, not objects themselves as I mistakenly did.

Therefore, instead of the previous approach

validations() {
            return {
                email: { required, email },
                password: {
                    required,
                    passwordValidators
                },
                firstName: { required },
                lastName: { required },
                confirmPassword: { required, sameAsPassword: sameAs(this.password) }
            }
        },

I needed to implement this corrected version

validations() {
            return {
                email: { required, email },
                password: {
                    required,
                    ...passwordValidators //a crucial difference lies here
                },
                firstName: { required },
                lastName: { required },
                confirmPassword: { required, sameAsPassword: sameAs(this.password) }
            }
        },

What did I do differently? By utilizing the spread operator, I included the necessary custom validators from the passwordValidators object inside the password object.

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

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

Tips for dynamically updating localeData and LOCALE_ID for i18n websites during the build process in Angular 9

I am currently developing an application that needs to support multiple languages, specifically up to 20 different languages. The default language set for the application is en-US. The translated versions are generated successfully during the build proces ...

Having trouble reaching external methods in Vue with Echarts OnClick Methods?

Hey there! I've been working on integrating Echarts into a Vue application, and I've encountered a bit of a roadblock. Specifically, I'm trying to capture the item clicked on one of the charts and then pass that data back to the parent compo ...

GAS: What strategies can I implement to optimize the speed of this script?

I have a sheet with multiple rows connected by "";" and I want to expand the strings while preserving the table IDs. ID Column X: Joined Rows 01 a;bcdfh;345;xyw... 02 aqwx;tyuio;345;xyw... 03 wxcv;gth;2364;x89... function expand_j ...

Send a collection of objects by submitting a form

I have a component with the following html code. I am attempting to dynamically generate a form based on the number of selected elements, which can range from 0 to N. <form #form="ngForm" id="formGroupExampleInput"> <div class="col-xs-5 col-md- ...

Tips for passing dynamic latitude and longitude values to a JavaScript function within an AngularJS framework

I am facing an issue with displaying a dynamic marker on Google Maps. I can show a static lat long marker, but I am struggling to pass dynamic lat long values to the function. How can I pass {{names.lat}}, {{names.longitude}} to the function so that I can ...

Check if an object is already in an array before pushing it in: JavaScript

Summary: I am facing an issue with adding products to the cart on a webpage. There are 10 different "add to cart" buttons for 10 different products. When a user clicks on the button, the product should be added to the this.itemsInCart array if it is not a ...

Infinite loop triggered by jQuery dropdown menu on page resize was causing an issue

I have been working on developing a navigation menu for a website that displays as a horizontal bar on larger screens, but transforms into a jQuery dropdown menu when the window width is less than 980px. During initial page load with a window width below ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

Should an HTML canvas in Angular be classified as a Component or a Service?

I have a basic drawing application that uses an MVC framework in TypeScript, and I am looking to migrate it to Angular. The current setup includes a Model for data handling, a View for rendering shapes on the canvas, and a Controller to manage interactio ...

Save data to local storage when the form is submitted, retrieve it when the page is reloaded

I need help with setting form data in local storage upon form submission and displaying a message in the console if the form has already been submitted when the page is refreshed. I am struggling to write the reload condition for this functionality. Here ...

Tips for efficiently utilizing mapActions in vue with Typescript class components!

Can someone please provide guidance on the correct way to use ...mapActions([]) within a Typescript vue class component? This is my current approach: <script lang="ts"> import { Component, Prop, Vue } from "vue-property-decorator"; import { mapActi ...

Unable to execute findOneAndUpdate as a function

I've been researching all morning and testing different solutions, but I'm still unable to resolve this issue. Every time I run the code below, I receive the error "TypeError: req.user.findOneAndUpdate is not a function": req.user.findOneAndUpd ...

The persistent issue of window.history.pushstate repeatedly pushing the identical value

I need some assistance with my Vue application. I am trying to update the URL when a user clicks on an element: const updateURL = (id: string) => { window.history.pushState({}, '', `email/${id}`); }; The issue I'm facing is th ...

Unable to capture screenshot of hovered element using Cypress

Having an issue with taking a screenshot of an element with a hover effect. The screenshots always come out without the hover effect applied. tableListMaps.lineWithText('Hello world', 'myLine'); cy.get('@myLine').realH ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Stop the replication of HTML/CSS styles during the extraction of content from a div

Is there a way to prevent the copying of CSS properties, such as font styles and sizes, when content is copied from a div? I want only the plain text to be copied to the clipboard, without any formatting applied. ...

I have my doubts about whether I am implementing the recapcha API correctly in a React application

I implemented the recapcha API in order to prevent bots from submitting posts on a forum site. As a new developer, I'm not sure if this is a real threat or not, as the users are limited to a maximum of 3 posts before they have to pay for more. I' ...

Ways to remove items from Vuex store by utilizing a dynamic path as payload for a mutation

I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element. Triggering the action deleteOption(path, key) { this.$store.d ...

Update the content of the document element by assigning it a lengthy string

I'm utilizing JQuery to dynamically assign content to a div element. The content has numerous lines with specific spacing, so this is the approach I am taking: document.getElementById('body').innerHTML = "Front-End Developer: A <br/> ...