1、html部分
<template>
<div>
<el-form ref="formRef" label-width="100px" :model="state.dialogForm" :rules="rules">
<el-form-item prop="oldPassword" label="旧密码">
<el-input v-model="state.dialogForm.oldPassword" size="large" type="password" clearable />
</el-form-item>
<el-form-item prop="password" label="新密码">
<el-input v-model="state.dialogForm.password" size="large" type="password" clearable />
</el-form-item>
<el-form-item prop="checkPassword" label="确认密码">
<el-input v-model="state.dialogForm.checkPassword" size="large" type="password" clearable />
</el-form-item>
<el-form-item>
<div>密码为6-18字母和数字组合</div>
</el-form-item>
</el-form>
<el-form-item>
<el-button @click="close(formRef)">取消</el-button>
<el-button type="primary" :loading="loading" @click="onSubmit(formRef)">确认</el-button>
</el-form-item>
</div>
</template>
2、ts部分
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
const formRef = ref<FormInstance>(); // form表单dom
// 检验确认密码框
const validateCheckPassword = (rule, value, callback) => {
if (value === "") {
callback(new Error("确认密码不能为空"));
} else if (state.dialogForm.password !== value && state.dialogForm.password !== '') {
callback(new Error("两次密码不一致!"));
} else {
callback();
}
}
// 检验新密码框
const validatePassword = (rule, value, callback) => {
var pwdRegex = new RegExp(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/);
if (value === "") {
callback(new Error("新密码不能为空"));
} else if (!pwdRegex.test(value)) {
callback(new Error("密码必须为6-18位字母和数字组合"));
} else if (state.dialogForm.oldPassword === value && state.dialogForm.oldPassword !== '') {
callback(new Error("新密码不能与旧密码相同"));
}else {
callback();
}
}
const rules = reactive<FormRules>({
oldPassword: [
{ required: true, message: '旧密码不能为空', trigger: 'blur' },
],
password: [
{ required: true, validator: validatePassword, trigger: 'blur' },
],
checkPassword: [
{ required: true, validator: validateCheckPassword, trigger: 'blur' },
],
})
const state = reactive({
dialogForm: { // 忘记密码表单
oldPassword: '', // 旧密码
password: '', // 新密码
checkPassword: '' // 确认密码
},
});
onMounted(() => {
})
/** 取消按钮 */
const close = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields() // 清除校验
}
/** 确认按钮 */
const onSubmit = async (formEl: FormInstance | undefined) => {
loading.value = true;
if (!formEl) return
await formEl.validate((valid, fields) => {
if (valid) {
state.dialogVisible = false // 关闭弹窗
} else {
return fields;
}
})
}
</script>