vue.js - 带有日期和字符串的表单集合验证 - Vuelidate
问题描述
我正在尝试用类似的方式验证一系列日期。
const data = [
{begin: new Date('2019-12-01'), place: '2'},
{begin: new Date('2019-12-03'), place: '3'}
... more values
];
// Elements inside data can be added or removed but will have at least one.
这里data[1][begin]
应该大于等于data[0][begin]
不等于。有没有办法做到这一点。文档讨论了动态验证,但我不确定如何通过收集来实现这一点。data[1][place]
data[0][place]
解决方案
您可以考虑在表单提交事件侦听器中实现自定义验证。
这可以通过循环遍历对象数组并成对比较项目来实现。
HTML
<form
id="app"
@submit="checkForm"
action="/someurl"
method="post"
>
<table border="1">
<tr v-for="(item,index) in dates" :key="index">
<td>
{{index}}
</td>
<td>
{{formatDate(item.begin)}}
</td>
<td>
{{item.place}}
</td>
</tr>
</table>
<input type="date" v-model="dateEntry"/>
<input type="text" v-model="placeEntry"/>
<button type="button" @click="addEntry">Add</button>
<p>
<br>
<input
type="submit"
value="Submit"
>
</p>
<p v-for="error in errorList">
{{error}}
</p>
</form>
JS
new Vue({
el: "#app",
data: {
errorList: [],
dateEntry: null,
placeEntry: null,
dates: [
{begin: new Date('2019-12-01'), place: '2'},
{begin: new Date('2019-12-03'), place: '3'}
]
},
methods: {
addEntry: function(){
if(this.dateEntry == null || this.dateEntry == "")
return false;
if(this.placeEntry == "")
return false;
this.dates.push({
begin: new Date(this.dateEntry),
place: this.placeEntry
});
this.dateEntry = null;
this.placeEntry= "";
},
checkForm: function(e){
var isValid = true;
var index = 0;
var nextIndex = 1;
this.errorList = [];
while(nextIndex < this.dates.length){
if(nextIndex < this.dates.length){
var isValidDate = this.validDate(this.dates[nextIndex].begin,this.dates[index].begin);
var isValidPlace = this.validPlace(this.dates[nextIndex].place,this.dates[index].place);
if(!isValidDate){
this.errorList.push("Invalid date on index " + nextIndex);
}
if(!isValidPlace){
this.errorList.push("Invalid place on index " + nextIndex);
}
}
index++;
nextIndex++;
}
if(!this.errorList.length){
this.errorList.push("All dates are valid");
return true;
}
e.preventDefault();
},
formatDate: function(date){
return date.toDateString();
},
validPlace: function(curPlace, prevPlace){
return curPlace != prevPlace;
},
validDate: function(curDate,prevDate){
try{
return curDate.getTime() >= prevDate.getTime();
}catch(e){
return false;
}
}
}
})
查看我创建的这个JS Fiddle来说明我的建议。
另一方面,如果您在运行时构建数组,则可以在将其添加到数组之前应用验证。
推荐阅读
- reactjs - 将 @babel/preset-react (https://git.io/JfeDR) 添加到 Babel 配置的“预设”部分以启用转换
- php - 我可以使用 Windows NETSH HOSTED NETWORK + PHP + MYSQL 实现强制门户吗?
- xtend - 我想在 xtend 中替换 .xml 文件中的特定内容
- azure - 不能创建超过 20 个 webjobs(全部被触发)
- php - 如何检查doc文件是真实的还是伪造的
- robotframework - 在使用 Edge 的机器人框架中,如何在 Pycharm 中更改重定向到我的 Runner 文件夹的下载路径?
- install4j - 使用 Install4j 进行双重签名
- numpy - Xarray 2维纬度变量
- javascript - cy.wrap() 在 mailosaur 中超时等待 4000 毫秒才能完成
- c# - 如何在asp .net core 3.1中将模型转换为xml