<template>
<a-form
ref="formRef"
name="custom-validation"
:model="formState"
:rules="rules"
v-bind="layout"
@finish="handleFinish"
@validate="handleValidate"
@finishFailed="handleFinishFailed"
>
<a-form-item has-feedback label="Password" name="pass">
<a-input
v-model:value="formState.pass"
type="password"
autocomplete="off"
/>
</a-form-item>
<a-form-item has-feedback label="Confirm" name="checkPass">
<a-input
v-model:value="formState.checkPass"
type="password"
autocomplete="off"
/>
</a-form-item>
<a-form-item has-feedback label="Age" name="age">
<a-input-number v-model:value="formState.age" />
</a-form-item>
<a-form-item :wrapper-col="{ span: 14, offset: 4 }">
<!-- <a-button type="primary" html-type="submit">Submit</a-button> -->
<a-button style="margin-left: 10px" @click="resetForm">Reset</a-button>
</a-form-item>
</a-form>
<a-button type="primary" @click="sub()">Submit</a-button>
</template>
<script>
export default {
data() {
let checkAge = async (_rule, value) => {
if (!value) {
return Promise.reject("Please input the age");
}
if (!Number.isInteger(value)) {
return Promise.reject("Please input digits");
} else {
if (value < 18) {
return Promise.reject("Age must be greater than 18");
} else {
return Promise.resolve();
}
}
};
let validatePass = async (_rule, value) => {
if (value === "") {
return Promise.reject("Please input the password");
} else {
if (this.formState.checkPass !== "") {
this.$refs["formRef"].validateFields("checkPass");
}
return Promise.resolve();
}
};
let validatePass2 = async (_rule, value) => {
if (value === "") {
return Promise.reject("Please input the password again");
} else if (value !== this.formState.pass) {
return Promise.reject("Two inputs don't match!");
} else {
return Promise.resolve();
}
};
return {
layout: {
labelCol: {
span: 4,
},
wrapperCol: {
span: 14,
},
},
formState: {
pass: "",
checkPass: "",
age: undefined,
},
rules: {
pass: [
{
required: true,
validator: validatePass,
trigger: "change",
},
],
checkPass: [
{
validator: validatePass2,
trigger: "change",
},
],
age: [
{
validator: checkAge,
trigger: "change",
},
],
},
};
},
methods: {
handleFinish() {
console.log("handleFinish");
},
handleFinishFailed() {
console.log("handleFinishFailed");
},
resetForm() {
console.log("resetForm");
},
handleValidate() {
console.log("handleValidate");
},
sub() {
console.info("sub");
this.$refs["formRef"]
.validate()
.then(() => {
console.info("通过");
})
.catch(() => {
console.info("不通过");
});
},
},
};
</script>