登录(三)02-登录表单验证——实例-yup方式 & 表单验证流程

本文介绍了如何使用Yup和formik库来实现登录表单的验证。首先,通过yarn安装yup,然后在withFormik高阶组件中配置validationSchema,设置用户名和密码的验证规则。接着,利用React组件的handleBlur事件处理表单字段的失焦,并通过props获取errors和touched来显示验证错误信息。最后展示了具体的Yup验证规则,如用户名和密码的长度限制。当表单提交时,会触发自定义的handleSubmit函数,该函数处理登录请求并处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

登录表单验证——实例-yup方式 & 表单验证流程

  1. 安装:yarn add yup ,导入 Yup
  2. 在 withFormik 中添加配置项 validationSchema,使用 Yup 添加表单校验规则。
  3. 在 Login 组件中,通过 props 获取到 errors(错误信息)和 touched(是否访问过,注意:需要给表单 元素添加 handleBlur 处理失焦点事件才生效!)。
  4. 在表单元素中通过这两个对象展示表单校验错误信息
render() {
    const {
      values,
      handleSubmit,
      handleChange,
      handleBlur,
      errors,
      touched
    } = this.props
    // console.log(values)

    return (
      <div className={styles.root}>
        {/* 顶部导航 */}
        <NavBar className={styles.navHeader} mode="dark">
          账号登录
        </NavBar>
        <WhiteSpace size="xl" />

        {/* 登录表单 */}
        <WingBlank>
          <form onSubmit={handleSubmit}>
            <div className={styles.formItem}>
              <input
                onBlur={handleBlur}
                value={values.username}
                className={styles.input}
                name="username"
                placeholder="请输入账号"
                onChange={handleChange}
              />
            </div>
            {/* 长度为5到8位,只能出现数字、字母、下划线 */}
            {touched.username && errors.username && (
              <div className={styles.error}>{errors.username}</div>
            )}
            <div className={styles.formItem}>
              <input
                value={values.password}
                onBlur={handleBlur}
                onChange={handleChange}
                className={styles.input}
                name="password"
                type="password"
                placeholder="请输入密码"
              />
            </div>
            {/* 长度为5到12位,只能出现数字、字母、下划线 */}
            {touched.password && errors.password && (
              <div className={styles.error}>{errors.password}</div>
            )}
            {/* <div className={styles.error}>账号为必填项</div> */}
            <div className={styles.formSubmit}>
              <button
                className={styles.submit}
                type="submit"
                onSubmit={this.handleLogin}
              >
                登 录
              </button>
            </div>
          </form>
          <Flex className={styles.backHome}>
            <Flex.Item>
              <Link to="/registe">还没有账号,去注册~</Link>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
export default withFormik({
  mapPropsToValues: () => ({ username: '', password: '' }),
  validationSchema: yup.object().shape({
    username: yup
      .string()
      .required('账号为必填项')
      .matches(REG_UNAME, '长度为5~8位,字母数字下划线'),

    password: yup
      .string()
      .required('密码为必填项')
      .matches(REG_PWD, '密码长度为5~12位字母数字下划线')
  }),
  handleSubmit: async (values, formikBag) => {
    const { username, password } = values
    const res = await axios.post(`http://localhost:8080/user/login`, {
      username,
      password
    })
    // console.log(res)
    const { status, body, description } = res.data
    if (status === 200) {
      window.localStorage.setItem('token', body.token)
      formikBag.props.history.push('/')
    } else {
      Toast.info(description, 1)
    }
  }
})(Login)
  • 表单验证流程

    • 基于formik进行表单数据绑定
      • mapPropsToValues
      • handleSubmit
    • 在表单中绑定相关信息
      • values.username
      • values.password
      • handleChange
    • 基于yup进行具体的验证规则配置
      • 安装并导入yup
        • import * as yup from ‘yup’
      • 通过yup的API配置验证规则
      • validationSchema
    validationSchema: yup.object().shape({
      username: yup.string().required('用户名不能为空').matches(REG_UNAME, '用户名必须是5-8个字符(字符、数字或者下划线)'),
      password: yup.string().required('用户名不能为空').matches(REG_PWD, '用户名必须是5-12个字符(字符、数字或者下划线)')
    })
    
    • 表单中进行信息绑定
      • handleBlur 失去焦点事件绑定
      • touched 记录验证的信息
      • errors 验证的结果信息
    • 指定提示信息位置
    {touched.password && errors.password && <div className={styles.error}>{errors.password}</div>}
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值