Antd-表单验证
基础版本验证
Form.Item 里面写规则 rules
rules 里面是规则
<Form.Item
name="username"
rules={[
{
required: true,
message: '用户名必须填写!', //失败时候返回的错误信息
},
{
pattern: new RegExp(
'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.[a-zA-Z0-9]{2,6}$',
'g'
),
message: '用户名必须是邮箱',
},
]}
>
<Input
prefix={<UserOutlined className="site-form-item-icon" />}
placeholder="用户名"
/>
</Form.Item>
自定义验证(重点)
rule 规则
validator 验证规则
Input 后面必须写 onBlur 失去焦点的方法
function useText() {
const [form] = Form.useForm()
const [password, setPassWord] = useState('')
const onFinish = (values) => {
console.log('Received values of form: ', values)
}
//验证密码函数
function validatePassWord(rule, value) {
if (value) {
if (value !== '123') {
setPassWord({
validateStatus: 'error',
errorMsg: '密码只能是123',
})
} else {
setPassWord({
validateStatus: 'success',
errorMsg: null,
})
}
} else {
setPassWord({
validateStatus: 'error',
errorMsg: '密码不能为空',
})
}
}
//失去焦点
function handlelostfocus() {
//不能判断error 只能判断success
if (
username.validateStatus === 'success' &&
password.validateStatus === 'success'
) {
setdisableflag(false)
} else {
setdisableflag(true)
}
}
return (
<Form.Item
name="password"
rules={[
{
validator: async (rule, value) => {
validatePassWord(rule, value)
},
},
]}
help={password.errorMsg}
validateStatus={password.validateStatus}
>
<Input
prefix={<LockOutlined className="site-form-item-icon" />}
type="password"
placeholder="Password"
onBlur={handlelostfocus}
/>
</Form.Item>
)
}