Creating unique validation rules using VeeValidate 3 and vue.js

I have a form where I need to establish specific rules.

For instance, consider the following code snippet:

<label class="form-label">Price range from</label>
<validation-provider rules="required_if:price_to" name="Price range from"
        v-slot="{ errors }">
    <input v-model="price_range_from" type="number" ref="price_from">
    <span class="validation-error form-span">{{ errors[0] }}</span>
</validation-provider>
        </div>
        <div class="ml-2 w-100">
<label class="form-label">Price range to</label>
<validation-provider name="Price range to"
                                             v-slot="{ errors }">
    <input v-model="price_range_to" type="number" class="form-control"
                   ref="price_to" name="price_range_to">
    <span class="validation-error form-span">{{ errors[0] }}</span>
</validation-provider>

From these form elements, I aim to define a custom rule with the following conditions:

  • The input field for price_range_from must be required if the price_range_to field is not empty.
  • The value in the price_range_from input cannot exceed the value in the price_range_to input.
  • This restriction applies both ways.

Incorporating a script to handle these validations:

import {ValidationProvider, ValidationObserver, extend} from 'vee-validate';
import * as rules from "vee-validate/dist/rules";
import {required} from 'vee-validate/dist/rules';

Object.keys(rules).forEach(rule => {
extend(rule, rules[rule]);
});

extend('required', {
...required,
message: 'This field is required'
});

I attempted to consult the documentation at [ but struggled to find guidance on creating custom rules.

If someone could provide an example that clarifies this concept, it would greatly assist me in advancing and developing more tailored rules.

Answer №1

If you want to achieve this functionality, you can target other fields by following this guide:

import { extend } from 'vee-validate';

extend('password', {
  params: ['target'],
  validate(value, { target }) {
    return value === target;
  },
  message: 'Password confirmation does not match'
});

...

<ValidationObserver>
  <ValidationProvider rules="required|password:@confirm" v-slot="{ errors }">
    <input type="password" v-model="password">
    <span>{{ errors[0] }}</span>
  </ValidationProvider>


  <ValidationProvider name="confirm" rules="required" v-slot="{ errors }">
    <input type="password" v-model="confirmation">
    <span>{{ errors[0] }}</span>
  </ValidationProvider>
</ValidationObserver>

To understand further how it functions, refer to the documentation. Essentially, @confirm is translated to target in the custom rule, corresponding to the input's name attribute.

The validate function within the custom rule simply returns a boolean indicating the validity of the field. You have the flexibility to incorporate any custom logic as needed and ensure it returns a boolean.

In your specific scenario where two different error messages are required, consider creating two separate custom rules for better management.

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

Unable to save captured signature image during saveEvent function in React Native

I am a beginner in the world of React Native and I am facing an issue with saving a signature image. It seems like the function responsible for this task is not being called properly. I suspect there might be an issue with the onPress event handler, as whe ...

Is there a way to filter and tally the JSON objects that have latitude and longitude within a 10km radius from the

I'm currently working on filtering and counting objects from an API endpoint that fall within a 10km radius of the specified origin. My main challenge lies in correctly filtering the API results and tallying the number of matching items. While I succ ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

Caution: An invalid next.config.js file has been detected while running the Next.js project

Whenever I try to run my project, I encounter the following three warnings: 1- warn - We found some invalid options in your next.config.js file. The property webpack5 is not recognized and may cause issues (allowed properties are: amp, analyticsId, assetP ...

Tips for personalizing the tooltip on a line chart in Vue.js using Chart.js

Attempting to create a line graph using chart js and vue, but new to both technologies. In the chart below, I am trying to change the tooltip to display "10 Answers July 19, 2023". I have attempted to use the beforeLabel and afterLabel options without succ ...

What is the best way to troubleshoot a quasar typescript file type error?

Currently, I am delving into Quasar using TypeScript and encountering a type error while working on file uploads. Here is the snippet of my code where the type error arises specifically in the parameter of the form.append() method. The error message read ...

Navigating through the sidebar on Next.js

I am currently exploring how to utilize next.js routes for dynamically populating a sidebar component with route instructions. The goal is to have the main div display the relevant component when a sidebar option is clicked. While I've come across tu ...

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

Unable to locate "Gruntfile.js" Node module for task execution

I am currently in the process of developing a module that enables node to execute Grunt tasks via the command line. This Node module is globally installed at : C:\Users\pcharpin\AppData\Roaming\npm\node_modules\task-app ...

Determining if the device is connected to the internet

Is there a way to create a unique code using HTML, JavaScript, or jQuery that executes a random action when the website detects that the device is offline? ...

I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // ...

Learn how to dynamically disable a button using jQuery within the Materialize CSS framework

While attempting to disable a button in Materialize CSS using jQuery, I encountered an issue. Despite following the documentation found here, it seems that simply adding the 'disabled' class does not automatically disable the button as expected. ...

Accessing a factory's functions within itself in Angular

I'm really trying to understand how all of this operates. It seems like it should be working as intended. I have an Auth factory that, when the jwt token expires, calls its 'delegate' method which obtains a new token using the refresh token. ...

Generating small image previews in JavaScript without distorting proportions

I am currently working on a client-side Drag and Drop file upload script as a bookmarklet. To prepare for the upload process, I am utilizing the File API to convert the images into base64 format and showcase them as thumbnails. These are examples of how m ...

Decoding user input parameters within a vue module

It seems like I am hitting a wall when it comes to finding solutions for this particular issue. Currently, I have a component that is supposed to retrieve data from a file and display it. My intention is to only pass the filename to the component so that ...

Ajax alert: The index 'id' is not defined

I'm currently learning PHP and scripting, but I am encountering some difficulties when it comes to sending information to PHP. I would appreciate any help you can offer. Thank you for your assistance. Here is the issue at hand: Error Message: Noti ...

Unable to retrieve the .attr() from a button that was created using handlebars

I am currently working on developing a web scraper as part of a homework task that involves using Express, Mongoose, Cheerio/axios, and Handlebars. In my "/" route, I retrieve the Mongoose objects and use Handlebars to display them on the page in individua ...

How can I track and log the name of the country each time it is selected by a click?

I'm currently utilizing VueJS along with a REST API and axios to retrieve the list of countries, then showcasing them in card format on the webpage. However, I am facing a challenge in creating a history list that captures the last 5 countries clicked ...

Retrieving data from Immediately Invoked Function Expressions

I've been working with a closure that looks like this: var Container = (function () { var variable; var changeVariable = function () { variable = 5; }; return { variable: variable, changeVariable: changeVariable }; ...

Retrieving values of checked boxes in a table using JavaScript

While using the select method, I had this line of code: Person_name = $('#selectedPerson').val() When selecting 2 values, person_name.length displays as 2. Recently, I switched to checkboxes displayed in a table. However, when I use person_name ...