Attach a validation rule to form a field programmatically

I use VeeValidate to do some validation on a form made using Vue.js. I configured it to display a range with an error message related to the input 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 are configured the same and they all work correctly. The problem occurs when I try to add a validation rule for the above input, which requires a date-between rule that uses the year from today as the maximum value.

date_between:{min,max}

The v-validate attribute accepts a string of validation rules enclosed in | . There is a way to dynamically add rules through a validation instance that automatically binds to the Vue instance.

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

I tried to make the code below in the 'created' and 'mount' hooks , and none of them gave the results I'm looking for.

 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 name of an object in my component data object this.$validator.attach('panelData.AnalysisDate', 'date_between:2001-01-01,' + yearFromTodayStr, { prettyName: 'Analysis Date' }); 

It is annoying that the code works, because if I use the console (chrome) to insert my code, it gives me the desired results when everything is displayed on the screen. I'm not sure if I use the right lifecycle hooks.

enter image description here

+5
source share
1 answer

The way I got around this seems to be hacked, but I couldn't get it to work with my original approach.

For date fields requiring dynamic range, I ended up using the directive style rule string and combined the computed property.

For instance:

  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> 
0
source

Source: https://habr.com/ru/post/1265621/


All Articles