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

Upon clicking the link, the JavaScript functionality failed to activate

When I click on a link and try to add a class, it's not working. I want to create a "modal" div. Here is the PHP/HTML code: <?php if(isset($_GET['ido'])) { ?> <div id="modal" class="modal" style="background: blue; width: 1 ...

Having trouble setting breakpoints in Chrome DevTools for my Vue application

Recently, I've encountered an issue where I am unable to place breakpoints in my Vue components as all the line numbers are greyed out. This problem started after updating Chrome to version 102.0.5005.63 from 86.0.4240.75. Could this be related to usi ...

The issue of drop shadows causing links to not work properly in Internet Explorer

I am currently working on a website design that features a fixed menu positioned behind the body. When the menu icon is clicked, some jQuery code shifts the body to the left. To create the effect of the fixed menu being positioned underneath, I have added ...

Building a personalized django widget to enhance functionality on other websites

Currently, I am in the process of developing a new website that includes user statistics. My goal is to create a widget that can be embedded on other websites using JavaScript to pull data from my server and display the statistics for a specific user. Howe ...

The Dysfunction of JQuery UI 1.12.1 Autocomplete

I am encountering some challenges with implementing JQuery UI. The version of JQuery UI I am using is 1.12.1, the latest one available. I have downloaded the autocomplete feature along with all other necessary widgets. In my project, I have placed jquery ...

instructions on how to exclusively close a bracket within a double bracket in a regular expression match

const input = "example(1)(2)example(3)example(4)(5)example(6)(7)example(8)example(9)" const regexp = new RegExp(????) // <-- need help with this input.match(regexp) result: [example(1)(2), example(3), example(4)(5), example(6)(7), example(8), example( ...

Upon utilizing JSON.parse in Express, an unexpected token < in JSON was encountered at position 0 while attempting a client side fetch POST

I'm trying to send a basic object through a fetch request to my express server, but I keep encountering an error when attempting to log it. Currently, if I log req.body (with the header 'Content-Type': 'application/x-www-form-urlencode ...

Stop automatic scrolling when the keyboard is visible in Angular

I have created a survey form where the user's name appears on top in mobile view. However, I am facing an issue with auto scroll when the keyboard pops up. I want to disable this feature to improve the user experience. <input (click)="onFocusI ...

Manipulating the DOM in AngularJS Directives without relying on jQuery's help

Let's dive right in. Imagine this as my specific instruction: appDirectives.directive('myDirective', function () { return{ restrict: 'A', templateUrl: 'directives/template.html', link: functio ...

Retrieve information from a MySQL database and integrate it into a different application

This php script is used to generate a table with a "book" button next to each row. The goal is to extract the values of "phase" and "site" from the specific row where the "book" button is clicked, and transfer them to another form (in "restricted.php") fo ...

Is there a way to successfully implement mouseover/mouseout functionalities while also resizing?

I've been working on a dropdown menu that functions well on both mobile and desktop devices. However, I have encountered an issue with resizing. Even when the screen size is reduced to mobile dimensions, the mouseover and mouseout functions continue t ...

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

Creating a stunning horizontal bar chart with the react-d3-components framework

I am currently implementing a D3 chart using the react-d3-components library. So far, I have successfully generated a vertical bar chart. However, my specific requirement is to create a horizontal bar chart. import React from 'react'; import Reac ...

What are the steps to view my HTML webpage on a smartphone?

Recently, I successfully created an HTML webpage with CSS and JS that looks and functions perfectly on my PC. However, when attempting to access it on my phone, I encountered some issues. Despite transferring all the necessary files to my phone, only the ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

The Final Div Fluttering in the Midst of a jQuery Hover Effect

Check out my code snippet here: http://jsfiddle.net/ZspZT/ The issue I'm facing is that the fourth div block in my example is flickering quite noticeably, especially when hovering over it. The problem also occurs occasionally with the other divs. Ap ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

Exploring the functionalities of ng-value and ng-model in text input form fields

As I create a form to update information in a database, everything seems to be functioning properly. The selected data is being retrieved correctly; however, it is not displaying in the text inputs on the webpage. Although the information appears correct ...

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...