Programmatically link validation rules to form fields

I have implemented validation in a form using VeeValidate with Vue.js. Each input displays an error message related to the specific field where the error occurred.

<div class="input-group">
  <input type="date" 
         class="form-control" 
         name="panelData.AnalysisDate" 
         data-vv-as="Analysis Date" 
         v-model="panelData.AnalysisDate"
         v-validate="'required|date_format:YYYY-MM-DD'">
</div>
<span v-show="errors.has('panelData.AnalysisDate')" class="redText">{{errors.first('panelData.AnalysisDate')}}</span>

All inputs follow the same setup and are functioning correctly. However, when I try to apply a validation rule that requires a date-between rule with the max value as one year from today's date, I encounter an issue.

date_between:{min,max}

The v-validate attribute accepts a string of rules delimited by |. It is possible to dynamically add rules using the validator instance attached to the Vue instance.

$validator.attach({field}, {rules list}, {options})

I attempted to add the following code within both the 'created' and 'mounted' lifecycle hooks, but did not achieve the desired outcome.

var today = new Date();
var yearFromToday = new Date(today.getFullYear() + 1, today.getMonth(), today.getDate());
    
var yearFromTodayStr = yearFromToday.toISOString().substring(0, 10);
//'this' refers to the current view instance
//'panelData' is the object in my component's data
this.$validator.attach('panelData.AnalysisDate', 'date_between:2001-01-01,' + yearFromTodayStr, {
        prettyName: 'Analysis Date'
    });

Interestingly, the code does work when manually inserted via the console (chrome) after rendering the screen. I suspect there may be an issue with the lifecycle hooks being used.

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

Answer №1

I had to think outside the box to solve this issue as my original method was not effective.

To handle date fields with a dynamic range requirement, I opted for a creative solution by combining directive style rules string and a computed property.

Here is an example of how I approached it:

  computed: {
    ninetyNineYearsAgo() {
      return new Date().getFullYear() - 99;
    },
    eighteenYearsAgoFormatted() {
      let eighteenYearsAgo = new Date().getFullYear() - 18;
      let todayISODate = new Date().toISOString().split('T')[0];
      return eighteenYearsAgo + '-' + todayISODate.split('-')[1] + '-' + todayISODate.split('-')[2];
    }
  }

<div class="input-group">
  <input type="date" 
         class="form-control" 
         name="panelData.AnalysisDate" 
         data-vv-as="Analysis Date" 
         v-model="panelData.AnalysisDate"
         v-validate="'date_format:YYYY-MM-DD|date_between:' + ninetyNineYearsAgo +'-01-01,'+ eighteenYearsAgoFormatted + ',true'">
</div>

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

Exploring the use of the Next.js page router for implementing internationalization (i18

I need assistance implementing Dutch and English language translations for my entire website. Can anyone provide guidance? I have tried using i18n localizely, but it only works for individual pages. I am looking to implement translations on a larger scale ...

In both Chrome and Edge, the default value for the <select> tag is successfully set, however, this functionality is not working in

I have defined two values in the created method, 2018 and My Name, and assigned them to separate data properties. These data properties are then passed as v-bind to a component. The issue I am facing is that in Chrome and Edge, both values are set as defa ...

X-ray Picker failing to retrieve a value

I am currently using the most recent version of the x-ray npm module in the code snippet below. Despite my expectations, the Meta and Metatags elements remain empty when I print out obj. Can anyone help me identify what I might be missing? var Xray = req ...

Having trouble with the downloadUrl function when trying to generate a Google map locator in Opencart?

Currently, I am working on the development of a website using opencart at Within the dealers.php file, there is a function named query() which searches postcodes in the database to retrieve store location results and outputs them in XML format. For exampl ...

Extracting POST information through PHP's AJAX Request

I am facing an issue where I keep receiving null values when using the following code: Here is my Ajax request: formData = { u: "3959eeadb32e02b85a792e21c", id: "6d7613df26" }; $.ajax({ ...

Updating Hidden Field Value to JSON Format Using jQuery and JavaScript

var jsonData = [{"Id":40,"Action":null,"Card":"0484"}]; $('#hidJson', window.parent.document).val(jsonData); alert($('#hidJson', window.parent.document).val()); // displays [object Object] alert($('#hidJson', window.parent.doc ...

Is there a way to simulate a click event (on a file type input) within a promise?

I've been struggling with this issue for a long time and have not been able to find a solution. The problem arises when attempting to trigger a click event on a file input type from within a promise. When I directly trigger the event inside the promis ...

Having trouble accessing data beyond the login page using Node/Express

Currently in an unusual situation. I am developing a backend and frontend that connects to a third-party RESTFUL API managing some hardware. The third-party API is hosted on your local system as a webserver, meaning HTTP requests are directed to "localhost ...

The afQuickField in Meteor is unable to locate the function when using the onfocus feature

I'm currently working on implementing a dynamic help feature that changes when the focus shifts using Meteor AutoForms. It's similar to the "Similar Questions" box that appears when you ask a question here. However, I'm encountering an issue ...

Ways to determine if the backbone.js model has been emptied

I often find myself wondering how to determine if a model has been cleared or is empty. For example, if I set the model with: model.set({name:'this is a test', id:1}); and then clear it with: model.clear(); ...

AngularJS Banner: Displaying Current Calendar Week and Increasing by 10 Days

I'm brand new to Angular and currently encountering some issues. Here's what I'm trying to create: I need to display the current Date: yyyy-MM-ss (Functional) I want to show the current Calendar Week: yyyy-Www (Not Working) When a butto ...

Guide to storing data in the browser's local storage with a Node.js Express backend

Up until this point, I relied on cookies to store preferences for my websites. However, as time has passed, the data stored in these cookies has grown too large and now exceeds the limit of 4096 characters. Therefore, I need to explore an alternative meth ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...

The query pertaining to Facebook redirect functionality

I have a Facebook ad with a URL encoded in it, and I need to extract the final destination URL that it redirects to using JavaScript in my Python program. The standard urllib2/mechanize methods don't work because of the JavaScript involved, and as a P ...

What is the best way to incorporate new data into localstorage in a React application?

My attempt to implement and add data into local storage has not been successful as it keeps updating the old data instead of adding new ones. Can someone please explain how to store an array of objects entered by a user in local storage using React JS? ...

Is there a way to set the same href link for the active class in the navbar using bootstrap-vue?

I am currently utilizing this navbar. It works fine when the href links are unique, but I encounter an issue when two pages share the same link - the active class is applied to both list items with that link in the manner I have written. Vue.component(& ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

Encountered an error while attempting to log in: TypeError: the property 'id' of null cannot be read

I am facing an issue with the login process, specifically getting a TypeError: Cannot read property 'id' of null error message. How can I debug and resolve this error? var cas = require('cas-client'); get_forward_url(function(forwardur ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...