官方文档:mirrors / yiminghe / async-validator · GitCodevalidate form asynchronous 🚀 Github 镜像仓库 🚀 源项目地址 ⬇https://gitcode.net/mirrors/yiminghe/async-validator?utm_source=csdn_github_accelerator
注意:当前示例有bug:先验证失败,再验证成功后,之前失败的消息没有清除
<template>
<div>
<div>
<input
type="text"
v-model="formData.username"
placeholder="请输入用户名"
/>
<span style="color: red" v-if="errorMessage.username">{{
errorMessage.username
}}</span>
</div>
<div>
<input
tyep="password"
v-model="formData.password"
placeholder="请输入密码"
/>
<span style="color: red" v-if="errorMessage.password">{{
errorMessage.password
}}</span>
</div>
<button @click="submit()">保存</button>
<button @click="reset()">重置</button>
</div>
</template>
<script setup>
import Schema from "async-validator";
import { reactive, ref } from "vue";
//控制输入框变红
const error_username = ref(false);
const error_password = ref(false);
// 表单对象
const formData = ref({
username: "",
password: "",
});
// 校验规则
const rules = ref({
username: {
required: true,
message: "姓名不能为空",
},
password: [
{
required: true,
message: "密码不能为空",
},
],
});
// 错误提示
const errorMessage = ref({
username: "",
password: "",
});
const validator = ref(new Schema(rules.value));
const submit = () => {
validator.value
.validate(formData.value, {
firstFields: true,
})
.then((data) => {
console.log("data:", data);
// 校验通过
console.log(" 校验通过,可以发起请求");
})
.catch(({ errors }) => {
// 校验未通过
// 显示错误信息
for (let { field, message } of errors) {
console.log("errors:", errors);
errorMessage.value[field] = message;
}
});
};
// 初始化表单
const initFormData = () => {
formData.value.username = "";
formData.value.password = "";
};
// 重置
const reset = () => {
initFormData();
// 清空校验错误提示
for (let key in errorMessage.value) {
errorMessage.value[key] = "";
}
};
</script>
<style scoped></style>