简体   繁体   中英

How to add validations for formik form with material UI

I am new to the formik and I am trying to add validations.

I have container which is like:

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}
      />
    )
  }
}

Now in the ForgotPasswordPage component

((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>
    )
  }
}

Now Here in this form I am trying to do few things like

adding validations, such that password and repeat password should be same and that is required. on Success of onSummit clear form.

How to add the validations in this form?

Thanks,

You can use yup library https://www.npmjs.com/package/yup . The library works well with formik, here you can see how to build easy validation form.

https://formik.org/docs/guides/validation

You can update validationSchema like this:

  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!"),
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM