基于表单值的Formik基本验证

时间:2019-09-15 11:41:05

标签: reactjs forms typescript formik yup

我的表格有点复杂。根据我正在发出的HTTP请求的类型,它具有3种基本类型:(POST_USER,PUT_USER,PUT_PASSWORD)。最重要的是,对于(POST_USER),我需要选择要创建的用户类型。在(BASIC和NON_BASIC)之间。

我正在使用ReactFormikYup进行验证。基于 HTTP_REQUEST 的验证工作正常。

问题是我要基于值形式检查,而我使用的ValidationSchema中的Formik却没有将它们作为道具传递。因此,我无法将参数传递给要传递给ValidationSchema的验证函数。这是我正在使用的用于ValidationSchema的函数。

export const VALIDATION_RULES = (execMode: executionMode): any => {
  switch (execMode) {
    case executionMode.PUT_USER:
      return Yup.object().shape({
        username: Yup.string()
          .trim()
          .required('Name is required'),
        email: Yup.string()
          .email()
          .nullable(),
        groups: Yup.array().required('Group is required')
      });
    case executionMode.PUT_PASSWORD:
      return Yup.object().shape({
        password: Yup.string()
          .trim()
          .required('Password is required'),
        confirmPassword: Yup.string()
          .trim()
          .required('Password confirmation is required')
          .oneOf([Yup.ref('password')], 'Passwords do not match')
      });
    default:
      return Yup.object().shape({
        type: Yup.mixed()
          .oneOf([AuthenticationType.BASIC, AuthenticationType.NON_BASIC])
          .required('Authentication Type is required'),
        username: Yup.string()
          .trim()
          .required('Name is required'),
        email: Yup.string()
          .email()
          .nullable(),
        password: Yup.string()
          .trim()
          .required('Password is required'),
        confirmPassword: Yup.string()
          .trim()
          .required('Password confirmation is required')
          .oneOf([Yup.ref('password')], 'Passwords do not match'),
        groups: Yup.array().required('Group is required')
      });
  }
};

executionMode是一个简单的Enum。我在上面的函数以及组件itslef中都使用了它:

enum executionMode {
  POST_USER = 'POST_USER',
  PUT_USER = 'PUT_USER',
  PUT_PASSWORD = 'PUT_PASSWORD'
}

export default executionMode;

这是我自己称为Formik的组件:

      <Formik
        initialValues={this.getDefaultValues(Mode)}
        validationSchema={VALIDATION_RULES(Mode)}
        onSubmit={this.handleSubmit}
        render={({ isSubmitting, values, status }) => (
          <Form>
            ..Form Related Code. Doesn't have anything to do with validation
          </Form>
        )}
      />

问题: 如上代码所述,该验证在NON_BASIC POST_USER表单之外的所有情况下均能正常运行。那里的问题是,由于对password和ConfirmPassword的验证仍然存在于validateSchema本身中,因此它不允许我创建User。

可能的解决方案: 1.我尝试使用Formik的validate,它将值作为prop传递,但是将错误映射到值的逻辑需要重新编写,这令人失望。最重要的是,还有一些我需要创建的自定义代码,例如处理validateSchema本身可以完美处理的onChange和onBlur错误。 2.我还尝试使用yup的when。没用它通过了验证,提交了表单,并返回服务器错误。

如果能提供帮助,我将不胜感激。请不要将此标记为重复。它不像使用when那样简单,并且在线文档非常有限,涉及如何使用validate以及我需要如何处理错误映射和处理事件更改。谢谢您的时间。

0 个答案:

没有答案