首页 > 其他分享 >5.Form表单验证实现【登陆】/ 登陆代码优化实现跳转home页

5.Form表单验证实现【登陆】/ 登陆代码优化实现跳转home页

时间:2023-02-28 18:12:46浏览次数:35  
标签:console log res callback 代码优化 登陆 跳转 const

1.这里使用Form表单的声明式验证与自定义验证

<Form.Item
    name="username"
    // 声明式验证,直接使用别人定义好的验证规则进行验证
    rules={[{ required: true, message: '用户名必须输入' },
        {min: 4, message: '用户名至少4位'},
        {max: 12, message: '用户名最多12位'},
        {pattern:/^[a-zA-Z0-9_]+$/, message: '必须由英文、数字或下划线组成'}
    ]}
>
    <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
</Form.Item>

<Form.Item
    name="password"
    rules={[{ validator: validatePwd }]}
>
    <Input
        prefix={<LockOutlined className="site-form-item-icon" />}
        type="password"
        placeholder="密码"
    />
</Form.Item>

/*
    对密码进行自定义验证
 */
const validatePwd = (rule, value, callback) => {
    console.log('validatePwd()', rule, value)
    if(!value){
        callback('密码必须输入')
    }else if(value.length < 4){
        callback('密码长度不能小于4位')
    }else if(value.length > 12){
        callback('密码长度不能大于12位')
    }else if(!/^[a-zA-Z0-9_]+$/.test(value)){
        callback('密码必须由英文、数字或下划线组成')
    }else{
        callback() // 验证通过
    }
    // callback('xxxxx') // 验证失败,并指定提示的文本
}

2.统一验证后,验证通过后再发送ajax请求

const onFinish = (values) => {
    // 统一验证成功
    console.log("validate success ", values)
};
const onFinishFailed = (errorInfo) => {
    // 统一验证失败
    console.log("validate failed error info ", errorInfo)
}

<Form
    name="normal_login"
    className="login-form"
    initialValues={{ remember: true }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
>

3. 登陆js代码优化且实现路由跳转如下:

import { Button, Form, Input, message } from 'antd';
import { useNavigate } from "react-router-dom”

// 默认暴露不需要写大括号,分别暴露需要解构,即大括号
import {reqLogin} from '../../api’

const navigate = useNavigate()
const onFinish = async (values) => {
    // 统一验证成功
    console.log("validate success ", values)
    // 请求登陆
    const {username, password} = values
    // 原始的写法
    // reqLogin(username, password).then(response => {
    //     console.log("登陆成功了!", response.data)
    // }).catch(error => {
    //     console.log("登陆失败了!", error)
    // })


    // async 与 await 简化 promise的使用,即取代了 .then .catch, 实际就是为了同步 如下:
    const response = await reqLogin(username, password)
    console.log("请求成功了!", response.data)
    const res = response.data
    if (res.code === 1){
        // 提示登陆成功
        message.success(res.message)
        // 跳转至管理界面
        navigate('/home')
    }else{
        // 登陆失败
        message.error(res.message)
    }
};
const onFinishFailed = (errorInfo) => {
    console.log("参数检验失败了!")
    // 统一验证失败
    console.log("validate failed error info ", errorInfo)
}

4.登陆的login.jsx文件内容如下【使用的是函数式组件】:

/*
    登陆的一级路由组件
 */
import React from 'react'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message } from 'antd';
import { useNavigate } from "react-router-dom"
import './login.css'
import logo from '../../assets/logo.png'
// 默认暴露不需要写大括号,分别暴露需要解构,即大括号
import {reqLogin} from '../../api'
import memoryUtils from "../../utils/memoryUtils"
import storageUtils from "../../utils/storageUtils"

function Login(){
    const navigate = useNavigate()

    // 先判断是否登陆,登陆直接跳转至 管理界面,为了有些用户直接在地址栏修改路径
    const user = memoryUtils.user
    if(user.username){
        // 这里的问题有待解决 即登陆成功后,在来到登陆页面是无法正常显示登陆,目的时调转至管理页面才可以
        navigate('/admin')
        return
    }
    // 点击登陆
    const onFinish = async (values) => {
        // 统一验证成功
        console.log("validate success ", values)
        // 请求登陆
        const {username, password} = values
        // async 与 await 简化 promise的使用,即取代了 .then .catch, 实际就是为了同步 如下:
        // ajax 优化2 直接返回的是 response.data
        const res = await reqLogin(username, password)
        console.log("请求成功了!", res)
        // const res = response.data
        if (res.code === 1){
            // 提示登陆成功
            message.success(res.message)
            // 跳转之前先保存user到内存
            memoryUtils.user = res.data
            // 保存user到local即本地
            storageUtils.saveUser(res.data)
            // 跳转至管理界面
            navigate('/admin')
        }else{
            // 登陆失败
            message.error(res.message)
        }
    };
    const onFinishFailed = (errorInfo) => {
        console.log("参数检验失败了!")
        // 统一验证失败
        console.log("validate failed error info ", errorInfo)
    }
    /*
        对密码进行自定义验证
     */
    const validatePwd = (rule, value, callback) => {
        console.log('validatePwd()', rule, value)
        if(!value){
            callback('密码必须输入')
        }else if(value.length < 4){
            callback('密码长度不能小于4位')
        }else if(value.length > 12){
            callback('密码长度不能大于12位')
        }else if(!/^[a-zA-Z0-9_]+$/.test(value)){
            callback('密码必须由英文、数字或下划线组成')
        }else{
            callback() // 验证通过
        }
    }
    return (
        <div className="login">
            <header className="login-header">
                <img src={logo} alt="logo"/>
                <h1>多-后台系统</h1>
            </header>
            <section className="login-content">
                <h2>用户登陆</h2>
                <Form
                    name="normal_login"
                    className="login-form"
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <Form.Item
                        name="username"
                        // 声明式验证,直接使用别人定义好的验证规则进行验证
                        rules={[{ required: true, message: '用户名必须输入' },
                            {min: 4, message: '用户名至少4位'},
                            {max: 12, message: '用户名最多12位'},
                            {pattern:/^[a-zA-Z0-9_]+$/, message: '必须由英文、数字或下划线组成'}
                        ]}
                    >
                        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[{ validator: validatePwd }]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="password"
                            placeholder="密码"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="login-form-button">
                            登陆
                        </Button>
                    </Form.Item>
                </Form>
            </section>
        </div>
    )
}
export default Login

 

标签:console,log,res,callback,代码优化,登陆,跳转,const
From: https://www.cnblogs.com/guo-s/p/17165485.html

相关文章

  • 5-1.后端实现登陆接口
    这里使用的是Flask框架+Python3.9版本+MySQL#ReactV5后台接口#登陆@app.route('/login',methods=["post"])deflogin():#获取登陆的用户信息,获取的......
  • 浅析JS代码优化(持续迭代)
    一、代码注释增加代码易读性及可维护性;一个人的工作经验从他的代码注释中可以很容易的看出来。二、拆分复杂的函数当一个消息(函数)需要太长时间才能处理完毕时,W......
  • 免登陆,用脚本提前修改微信、企业微信、QQ的聊天路径
    为什么要改聊天路径微信、企业微信、QQ的聊天记录默认都是放在登陆用户的文档目录下面的登陆用户的文档目录路径C:\Users\%USERNAME%\Documents在我的日常工作中,碰到......
  • 获取当前IP地址,跳转到对应城市网站
    1,通过获取当前IP地址2,调用新浪AIP,获取到当前城市3,将中文转换为拼音后跳转<?phpinclude'./pinyin.php';//获取当前ipfunctiongetIp(){$onli......
  • Vue2路由跳转传参,获取路由参数,Vue监听路由
    1this.$router.push({2//name:路由组件名3name:routeName,4query:{5mapId:this.mapId6}7})89this.$router.push({1......
  • uniapp app跳转至支付宝然后返回app
    有需求:用支付宝支付时(第一次支付需授权)跳转至支付宝授权,然后再返回app跳转支付宝:<button@click="toZFB">支付宝</button>toZFB(){leturls='https......
  • Java开发中要避免的坑和一些代码优化技巧
    1:动态SQL遇到的坑,先看下面OGNL表达式的说明。Anyobjectcanbeusedwhereabooleanisrequired.OGNLinterpretsobjectsasbooleanslikethis:Iftheobjecti......
  • Activity创建和跳转
    首先,在layout目录下创建XML文件方法一:方法二:快速创建Activity能够在清单文件上的activity自动配置Android:MainActivity3  创建与文件对应的Java代码创建并在acti......
  • uni-app:从webview跳转到应用内其他页面(hbuilderx 3.7.3)
    一,代码:1,页面代码:<template><view><web-view:fullscreen="true":style="{height:height+'px'}":webview-styles="webviewStyles":src='websrc'allow......
  • satoken实现登陆验证
    1.第一步导入依赖//Sa-Token权限认证,在线文档:https://sa-token.ccimplementation'cn.dev33:sa-token-spring-boot-starter:1.34.0'2.第二步配置文件server:......