使用formik和yup是为了解决react-form表单验证的繁琐
// 关键代码逻辑
//组件触发区
<TextFieldid="ResetEmail"type="email" label="E-mail"onChange={this.handleInputChange} value={ResetEmail}error={resetPasswordError}
/>//onchange触发事件handleInputChange = (value,field) =>{this.setState({[field]: value},()=>{setTimeout(()=>{if(field === 'Email'){this.checkInputEmail(value);}if(field === 'Password'){this.checkInputPassword(value);}if(field === 'ResetEmail'){this.checkResetPasswordEmail(value)}},600);});}// email 格式验证checkInputEmail(email){let errorMsg = '';let bool = false;if(email === undefined || email === ''){errorMsg = this.state.isLoginPage ? 'Email is required' : 'Please enter a valid email';}if(errorMsg === ''){let reg = /w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*/;bool = st(email);errorMsg = bool ? '' : 'Invalid email';}this.setState({ emailError: errorMsg });return bool;}
formik–prop-api链接:
yup-github链接:
// 引入所需
// useFormik()是一个自定义的 React 钩子
// 官网使用例子: { useFormik } from 'formik';
import * as yup from 'yup';// 定义所需要的formik-prop-api。可自查官网了解
/*
initialValues:初始化要的数据
onSubmit: 获得表单各个字段,自定义自己的业务操作
validationSchema: 结合yup的验证模式
*/
const {values,errors,touched,handleBlur,handleChange,handleSubmit} = useFormik({initialValues,onSubmit: handleFormSubmit,validationSchema: formSchema});// 初始话表单数据
const initialValues = {email: '',
};// yup规则,可以查yup-github链接看相关api使用。
const formSchema = yup.object().shape({// name: yup.string().required('${path} is required'),email: yup.string().email('invalid email').required('${path} is required'),
});/*
注意 '${path} is required'
使用字符串语法,而非es2015引进的模板字符串,
因为后者会在编译期就去链接对应的变量,但是 path
并非是预先定义的变量,所以为报错。
所以这里只是普通的字符串里使用了类似模板字符串的语法罢了。
*/// 组件使用<BazarTextField mb={1.5} name="email" label="Email" placeholder="exmple@mail" variant="outlined" size="small" type="email" fullWidth onBlur={handleBlur} onChange={handleChange} value={ail || ''} error={!!ail && !!ail} helperText={ail && ail} />
本文发布于:2024-01-30 21:41:00,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170662206323022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |