登录表单验证——实例-yup方式 & 表单验证流程
- 安装:yarn add yup ,导入 Yup。
- 在 withFormik 中添加配置项 validationSchema,使用 Yup 添加表单校验规则。
- 在 Login 组件中,通过 props 获取到 errors(错误信息)和 touched(是否访问过,注意:需要给表单 元素添加 handleBlur 处理失焦点事件才生效!)。
- 在表单元素中通过这两个对象展示表单校验错误信息
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
- 安装并导入yup
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>}
- 基于formik进行表单数据绑定