我试图验证仅用于输入数字的v-text-field,但不是必需的,但是规则拒绝通过验证。
我使用了v-form,v-text-field和v-text-field的规则。
<template>
<v-form ref="form">
<v-text-field
v-model="name"
:label="label"
:rules="rules"
@blur="changeValue"
clearable
></v-text-field>
<v-btn @click="send">submit</v-btn>
</v-form>
</template>
<script>
export default {
data() {
return {
name: "",
rules: [
v =>
v.length <= 50 || "maximum 50 characters",
v =>
(v.length > 0 && /^[0-9]+$/.test(v)) || "numbers only"
]
};
},
methods: {
changeValue(event) {
this.$emit("changeValue", event.target.value);
},
send() {
const valid = this.$refs["form"].validate(); // doesn't pass
if (valid) {
this.$store.dispatch("xxx", {
...
});
}
}
}
};
</script>
单击提交按钮后,将显示v-text-field的错误消息,并且valid
为假。
单击X(清除图标),控制台上还会显示错误消息:
"TypeError: Cannot read property 'length' of null"
答案 0 :(得分:4)
有点晚了,但是我已经用这个功能解决了:
post /api/du/v1
POST api/du/v1 {"name":"du1"}
答案 1 :(得分:1)
我用这种方式一种用于电子邮件,一种用于名称
nameRules: [
v => v.length <= 10 || 'Name must be less than 10 characters',
],
emailRules: [
v =>( v.length ===0 || /.+@.+/.test(v) ) || 'E-mail must be valid',
],