React Ts Antd实现密码多规则校验

本文介绍了如何在React应用中使用Hooks和antd库实现一个包含自定义密码规则验证的登录表单组件,包括正则表达式和状态管理。
摘要由CSDN通过智能技术生成

Hooks

import {useState} from "react";
import {FormItemProps, type FormProps, message} from "antd";

interface PasswordRegMatch {
    content: string
    reg:RegExp
    status: boolean
}

export type FieldType = {
    username: string
    password: string
    captcha: string
    remember: string
    nickname: string
};

export function useLogin() {
    const [passwrodRegMatches, setPasswrodRegMatches] = useState<PasswordRegMatch[]>([
        {
            reg:/[0-9]+/,
            content: "密码必须包含数字",
            status: false
        },
        {
            reg:/[a-z]+/,
            content: "密码必须包含小写字母",
            status: false
        },
        {
            reg:/[A-Z]+/,
            content: "密码必须包含大写字母",
            status: false
        },
        {
            reg:/[.@$!%*#_~?&^]+/,
            content: "密码必须包含特殊字符(.@$!%*#_~?&^)",
            status: false
        },
    ])
    const passwordRules: FormItemProps['rules'] = [
        {
            required:true,
            message:"密码不能为空!"
        },
        () => ({
            validator(_, value) {
                let level = 0
                const newMatches = passwrodRegMatches.map((match) => {
                    if (match.reg.test(value)) {
                        level++
                        match.status = true
                    }else{
                        match.status = false
                    }
                    return match
                })
                setPasswrodRegMatches(newMatches)
                if (value.length < 8 || value.length > 16 || !/^[a-zA-Z0-9.@$!%*#_~?&^]{8,16}$/.test(value) || level < passwrodRegMatches.length) {
                    return Promise.reject(new Error('密码必须包含数字、大写字母、小写字母、特殊字符(如.@$!%*#_~?&^)至少3种的组合且长度在8-16之间'));
                }
                return Promise.resolve()
            },
        }),
    ]
    return {
        passwordRules,
        passwrodRegMatches,
    }
}

页面

多余代码删除了

import React, {PropsWithChildren} from 'react';
import {Button, Checkbox, Col, Form, Input, Row} from 'antd';
import {debounce} from "lodash";
import {FieldType, useLogin} from "@/views/login/composable/use_login.tsx";
import {FrownOutlined, MehOutlined} from '@ant-design/icons';


interface Props extends PropsWithChildren {
    toRegister: () => void
}

// <FrownOutlined />
export const LoginForm: React.FC<Props> = ({toRegister}) => {
    const { passwordRules, passwrodRegMatches} = useLogin()
    return (

        <Form
            name="basic"
            labelCol={{span: 8}}
            wrapperCol={{span: 16}}
            style={{maxWidth: 600}}
            initialValues={{remember: true}}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
        >
            <Form.Item<FieldType>
                label="密码"
                name="password"
                rules={passwordRules}
            >

                <Row >
                    <Col span={8}>
                        <Input.Password/>
                    </Col>
                    <Col span={14} offset={2}>
                        <ul className="text-xs">
                            {passwrodRegMatches.map((match,index)=> {
                                return <li className={match.status ?"text-emerald-500":"text-gray-500"} key={index}>{match.content}{match.status ? <MehOutlined/>:<FrownOutlined/>}</li>
                            })}
                        </ul>
                    </Col>
                </Row>
            </Form.Item>
           
                    <Col>
                        还没有账号?点击<Button onClick={() => toRegister()} type="link" className="p-0">注册</Button>
                    </Col>
                </Row>
            <Form.Item wrapperCol={{span: 22, offset: 6}}>
                <Button type="primary" htmlType="submit" block>
                    登录
                </Button>
            </Form.Item>
        </Form>
    );
}

效果展示

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鲤余

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值