【发布时间】:2019-07-20 11:52:28
【问题描述】:
这个时间选择器组件是表单生成器的一部分。我传入一些项目,它们将被处理为文本输入、数字输入等。
由于您无法将验证函数存储到数据库中,我们将正则表达式模式存储到数据库中。对于此示例,我只想检查该字段是否为空。
表单生成一个能够验证输入的时间选择器组件。不幸的是,第一个输入的验证返回false。第二次更改时间时,它返回true。清除该字段也会返回true。
我创建了一个演示。消费组件使用此代码
<template>
<v-app id="inspire">
<TimeField
v-for="maskItem in maskItems"
:key="maskItem.fieldId"
:value="maskItem.value"
:rules="getValidation(maskItem)"
@input="onMaskItemValueUpdated(maskItem.fieldId, ...arguments)"
/>
</v-app>
</template>
<script>
import TimeField from "./components/TimeField";
export default {
components: {
TimeField
},
data: function() {
return {
maskItems: [
{
fieldId: 1,
value: null,
validation: [
{
pattern: new RegExp(".{1,}"),
message: "This field is required"
}
]
}
]
};
},
methods: {
getValidation: function(maskItem) {
return maskItem.validation.map(rule => value =>
(value && rule.pattern.test(value)) || rule.message
);
},
onMaskItemValueUpdated: function(fieldId, newValue) {
this.maskItems.find(
fieldToUpdate => fieldToUpdate.fieldId === fieldId
).value = newValue;
}
}
};
</script>
如果时间选择器应该显示特定语言环境的时间格式,它本身就能够格式化时间。格式化日期时,文本字段会将格式化的日期传递给验证。这是错误。为了处理这种行为,我创建了 getValidationRules 函数并将正确的值传递给验证。但是,它正在使用此代码
<template>
<v-menu :value="showMenu" max-width="290px">
<template v-slot:activator="{ on }">
<v-text-field
:value="formattedTime"
clearable
v-on="on"
:required="true"
:rules="formatBasedRules"
@input="selectValue"
></v-text-field>
</template>
<v-time-picker :value="value" @input="selectValue"/>
</v-menu>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ""
},
rules: {
type: Array,
default: () => []
}
},
data: function() {
return {
showMenu: false,
formatBasedRules: [true]
};
},
computed: {
formattedTime: function() {
// ... !! format time here !! ...
return this.value;
}
},
mounted: function() {
this.formatBasedRules = this.getValidationRules();
},
methods: {
selectValue: function(newValue) {
this.showMenu = false;
this.$emit("input", newValue);
this.formatBasedRules = this.getValidationRules();
},
getValidationRules: function() {
for (const rule of this.rules) {
const result = rule(this.value);
if (typeof result === "string") {
return [result];
}
}
return [true];
}
}
};
</script>
我创建了一个复制示例
https://codesandbox.io/s/menu-picker-validation-eorep
只需选择一个时间,您就会收到一条错误消息。选择另一个时间,验证将返回true。清除该字段也会返回true。
有人知道这里出了什么问题吗?
【问题讨论】:
标签: vue.js vuetify.js