@click="handleValidateButtonClick"> 验证
import { ref } from 'vue';
import { NForm, NRow, NCol, NButton, NFormItem, NInput, NSpace } from 'naive-ui';
import { FormInst, FormItemInst, FormItemRule, FormRules } from 'naive-ui';
interface ModelType {
age: string | null
password: string | null
}
const formRef = ref
const modelRef = ref
age: null,
password: null
});
function validatePasswordStartWith(
rule: FormItemRule,
value: string
): boolean {
return (
!!modelRef.value.password &&
modelRef.value.password.startsWith(value) &&
modelRef.value.password.length >= value.length
)
}
function validatePasswordSame(rule: FormItemRule, value: string): boolean {
return value === modelRef.value.password
}
const rules: FormRules = {
age: [
{
required: true,
validator(rule: FormItemRule, value: string) {
if (!value) {
return new Error('需要年龄')
} else if (!/^\d*$/.test(value)) {
return new Error('年龄应该为整数')
} else if (Number(value) < 18) {
return new Error('年龄应该超过十八岁')
}
return true
},
trigger: ['input', 'blur']
}
],
password: [
{
required: true,
message: '请输入密码'
}
],
reenteredPassword: [
{
required: true,
message: '请再次输入密码',
trigger: ['input', 'blur']
},
{
validator: validatePasswordStartWith,
message: '两次密码输入不一致',
trigger: 'input'
},
{
validator: validatePasswordSame,
message: '两次密码输入不一致',
trigger: ['blur', 'password-input']
}
]
}
function handleValidateButtonClick(e: MouseEvent) {
e.preventDefault()
formRef.value?.validate((errors) => {
if (!errors) {
console.log("验证成功");
} else {
console.log(errors)
console.log("验证失败");
}
})
}
//第一种方法
// .loginbox{
// width: 300px;
// height: 200px;
// border: 1px solid #ccc;
// margin: auto; /**这个居中对齐,需要使用margin position 与lef top rigth bottom一起使用 */
// left: 0px;
// top:0px;
// right: 0px;
// bottom: 0px;
// position: absolute;
// padding: 20px;
// border-radius: 5px;
// box-shadow: 0px 0px 10px rgba(0, 0, 0, .6);/**四周模糊 */
// }
//第二中方法
.loginbox {
position: absolute;
width: 300px;
height: 200px;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -150px;/**这种需要positon margin-top margin-left配合,先占据50%,然后左移动,上移动宽度和高度一半 */
border:1px solid #e3e323;
padding: 20px;
box-shadow: 0px 0px 10px rgba(0, 0, 0, .1);/**四周模糊 */
}