Vue简单的表单验证
前端验证必不可少~输入框验证vue文件部分:<form :model="form" :rules="rules" ref="form"><form-item :label="姓名" prop="name"><kc-input v-model="form.name"></kc-input></f...
·
前端验证必不可少~
输入框验证
vue文件部分:
<form :model="form" :rules="rules" ref="form">
<form-item :label="姓名" prop="name">
<kc-input v-model="form.name"></kc-input>
</form-item>
</form>
ts文件部分:
export default Vue.extend({
data() {
return {
form: {
name: "",
},
rules: {
name: [
{ required: true, message: "请输入姓名", trigger: "blur" },
],
}
}
},
methods: {
// 验证
submitForm(): void {
const form = this.$refs.form as Vue;
form.validate((valid: any) => {
if (valid) {
this.doSave();
} else {
return false;
}
});
},
doSave() {
console.log("验证ok");
},
},
});
其中,需要注意的是先定义验证规则rules,form-item标签上的prop属性的值是rules中定义的,这个name在form中和rules中都要保持一致。
下拉框的验证
在上面代码的基础上增加一个下拉框的验证。
vue文件部分:
<form :model="form" :rules="rules" ref="form" :class="$style.form">
<form-item :label="姓名" prop="name">
<kc-input v-model="form.name"></kc-input>
</form-item>
<form-item :label="课程" prop="courses">
<select v-model="form.courses" placeholder="请输入课程">
<option
v-for="item in courseOption"
:key="item.id"
:label="item.name"
:value="item.id"
>
</option>
</select>
</form-item>
</form>
ts文件部分:
interface Icourse {
id: string;
name: string;
selected: boolean;
}
export default Vue.extend({
data() {
const courseOption: Icourse[] = [{
id: "1",
name: "语文",
selected: false,
}, {
id: "2",
name: "数学",
selected: false,
}, {
id: "3",
name: "英语",
selected: false,
}];
return {
form: {
name: "",
courses: "",
},
courseOption,
rules: {
name: [
{ required: true, message: "请输入姓名", trigger: "blur" },
],
courses: [
{ required: true, message: "请输入课程", trigger: "change" },
],
}
}
},
// ...
});
这里,下拉框的验证和输入框的大致一样,都需要保持form中和rules中的courses相同,只是这儿是ts的写法,多了一个ts接口。
很明显,以上代码中data部分都是一层对象,如果有嵌套的对象出现,如何验证呢?
举个例子,
ts文件的data部分:
data() {
const student= {
info: {
name: "",
age: "",
}
cls: "",
school: "",
};
return {
student,
rules: {
"info.name": [
{ required: true, message: "请输入姓名", trigger: "blur" },
],
"info.age": [
{ required: true, message: "请输入年龄", trigger: "blur" },
],
"cls": [
{ required: true, message: "请输入班级", trigger: "blur" },
],
"school": [
{ required: true, message: "请输入学校", trigger: "blur" },
]
},
};
},
相应的vue文件部分:
<form :model="student" :rules="rules" ref="student">
<form-item :label="姓名" prop="info.name">
<kc-input v-model="student.info.name"></kc-input>
</form-item>
<form-item :label="年龄" prop="info.age">
<kc-input v-model="student.info.age"></kc-input>
</form-item>
<form-item :label="班级" prop="cls">
<kc-input v-model="student.cls"></kc-input>
</form-item>
<form-item :label="学校" prop="school">
<kc-input v-model="student.school"></kc-input>
</form-item>
</form>
其实很简单,会了就很简单~
关注我吧
关注「前端一起学」公众号 ,看着项目进阶学习,让我们一起学前端,一起进步。
更多推荐
已为社区贡献4条内容
所有评论(0)