[英]How to add validations for formik form with material UI
我是formik的新手,我正在嘗試添加驗證。
我有這樣的容器:
export default class ForgotPasswordContainer extends React.Component<
RouteComponentProps,
MyState
> {
constructor(props) {
super(props)
this.state = {
error: '',
success: ''
}
}
forgotPasswordSuccess = async result => {
if (result.Status === 'Successful') {
this.setState({
success: strings.emailSuccess
})
} else if (result.Status === 'Failed') {
this.setState({
error: result.ErrorAdmin
})
}
}
forgotPassword = async ({ variables }) => {
console.log(variables)
const url = `url to change password`
console.log(url)
try {
const result: any = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
mode: 'no-cors'
}
})
return {
data: {
login: await result.json()
}
}
} catch (err) {
this.setState({
error:
err?.response?.data?.error_description || err.message || strings.genericError
})
throw err
}
}
render() {
const { forgotPassword, forgotPasswordSuccess } = this
return (
<ForgotPasswordPage
onSubmit={forgotPassword}
error={this.state.error}
onForgotPasswordSuccess={forgotPasswordSuccess}
OnSuccess={this.state.success}
backgroundImage={LoginBackground}
logo={logo}
/>
)
}
}
現在在ForgotPasswordPage
組件中
((withFormik as any)({
mapPropsToValues: () => ({ username: '' })
validationSchema: Yup.object().shape({
username: Yup.string().required('Username is required!')
}),
handleSubmit: (values, { setSubmitting, props }) => {
const { onSubmit, onForgotPasswordSuccess } = props
onSubmit({ variables: values }).then(
result => {
setSubmitting(false)
onForgotPasswordSuccess(result.data.login)
},
() => {
setSubmitting(false)
}
)
},
displayName: 'LoginForm'
}))
export default class ForgotPasswordPage extends React.Component<MyProps> {
render() {
const {
error,
values,
touched,
errors,
dirty,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
logo,
headerLabel,
backgroundImage,
OnSuccess
} = this.props
return (
<Card
style={{ background: `url(${backgroundImage})` }}
className={css.backgroundCard}
alignItem='center'
justifyContent='center'>
<Card
className={css.loginCard}
variant='standard'
alignItem='center'
direction='column'>
{logo ? (
<Icon imageSrc={logo} className={css.logo} />
) : (
<div>
<div>
<Typography variant='h1'>{headerLabel}</Typography>
</div>
<div>
<Typography variant='h1'>Forgot Password</Typography>
</div>
</div>
)}
<form onSubmit={handleSubmit} className={css.loginForm}>
<Input
variant='standard'
textAlign='center'
placeholder='Username'
id='username'
name='username'
type='text'
value={values.username}
onChange={handleChange}
onBlur={handleBlur}
autoFocus
error={errors.username && touched.username}
/>
{error && (
<Typography variant='caption' classes={css.errorMsg}>
{error}
</Typography>
)}
{OnSuccess && (
<Typography variant='caption' classes={css.successMsg}>
{OnSuccess}
</Typography>
)}
<Button
variant='primary'
theme='light'
type='submit'
disabled={!dirty || isSubmitting || !!errors.username}>
<Typography variant='h1'>Send Password</Typography>
</Button>
</form>
</Card>
</Card>
)
}
}
現在以這種形式,我正在嘗試做一些事情,例如
添加驗證,這樣密碼和重復密碼應該是相同的,這是必需的。 onSummit 明確表格的成功。
如何在此表單中添加驗證?
謝謝,
您可以使用yup
庫https://www.npmjs.com/package/yup 。 該庫與 formik 配合得很好,在這里您可以看到如何構建簡單的驗證表單。
您可以像這樣更新validationSchema
:
validationSchema: Yup.object().shape({
username: Yup.string().required('Username is required!'),
password: Yup.string()
.min(7)
.max(255)
.required("Password is required"),
confirmPassword: Yup.string()
.min(7)
.max(255)
.oneOf([Yup.ref("password")], "Password's not match")
.required("Required!"),
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.