简体   繁体   English

如何在第一次提交时实现验证,然后在第二次使用 formik 后对更改进行验证

[英]How to achieve validation on submit for the first time, then validation on change after the second time using formik

So I am facing a couple of problems when trying to use formik to handle my input fields, basically after pressing on one input fields validation starts on the rest and I dont want that to happen.因此,在尝试使用 formik 处理我的输入字段时,我遇到了几个问题,基本上是在按下一个输入字段后,验证在 rest 上开始,我不希望这种情况发生。

Preferably for the first time validation should only take place onsubmit and then after that validation continues onchange.最好是第一次验证应该只在提交时进行,然后在验证继续更改之后进行。

Here is my code:这是我的代码:

logic:逻辑:

const CompanyProfile = () => {
  const CompanySchema = Yup.object().shape({
    name: Yup.string()
      .min(2, 'too short')
      .required(ERROR_REQUIRED),
    industry: Yup.string().notRequired(),
    address: Yup.string().notRequired(),
    crn: Yup.number().required(ERROR_REQUIRED),
    website: Yup.string().notRequired(),
    employeesNbr: Yup.string().required(ERROR_REQUIRED),
    phoneNumber: Yup.number().required(ERROR_REQUIRED),

    userRole: Yup.string().required(ERROR_REQUIRED),
    personCheck: Yup.boolean().required(ERROR_REQUIRED),
  });

  const formik = useFormik({
    initialTouched: false,
    validateOnChange: true,
    initialValues: {
      name: '',
      industry: '',
      address: '',
      crn: '',
      website: '',
      employeesNbr: '',
      phoneNumber: '',
      userRole: '',
      personCheck: false,
    },

    validationSchema: CompanySchema,
    onSubmit: values => {
      alert(JSON.stringify(values, null, 2));
    },
  });

  return (
    <Skeleton pageTitle={PAGE_TITLE_COMPANY_PROFILE}>
      <CompanyProfileForm formik={formik} />
    </Skeleton>
  );
};
export default CompanyProfile;

front-end前端

const CompanyProfileForm = ({ formik }: Props) => {
  const [modal, setModal] = useState(false);

  const { errors } = formik;

  const handleSubmit = () => {
    console.log(formik);
    formik.handleSubmit();
    if (
      !formik.errors.name &&
      !formik.errors.crn &&
      !formik.errors.employeesNbr &&
      !formik.errors.phoneNumber &&
      !formik.errors.userRole
    ) {
      setModal(true);
    } else setModal(false);
  };

  const handleModalClick = () => {
    setModal(false);
  };
  return (
    <div style={screenContainer}>
      {formik.errors.personCheck && modal && (
        <ModalPopup
          warningMessage={WARNING_CONFIRM_PERSON}
          onClick={handleModalClick}
          success={false}
        />
      )}
      <div style={inputDiv}>
        <div style={inputContainerLabel}>
          <Nunito16 style={labelStyle}>{COMPANY_DETAILS}</Nunito16>
        </div>
        <div style={inputFieldContainer}>
          <div style={firstInputColumn}>
            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>{COMPANY_FORM_INPUT_NAME}</Nunito20>
              <InputValidation
                type="text"
                name="name"
                value={formik.name}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.name}
                validationMessage={formik.errors.name}
              />
            </div>

            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>
                {COMPANY_FORM_INPUT_INDUSTRY}
              </Nunito20>
              <InputValidation
                type="text"
                name="industry"
                value={formik.industry}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.industry}
                validationMessage={ERROR_REQUIRED}
              />
            </div>

            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>
                {COMPANY_FORM_INPUT_ADDRESS}
              </Nunito20>
              <InputValidation
                type="text"
                name="address"
                value={formik.address}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.address}
                validationMessage={formik.errors.address}
              />
            </div>
            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>
                {COMPANY_FORM_INPUT_CR_NUMBER}
              </Nunito20>
              <InputValidation
                type="number"
                name="crn"
                value={formik.crn}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.crn}
                validationMessage={formik.errors.crn}
              />
            </div>
          </div>
          <div style={secondInputColumn}>
            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>
                {COMPANY_FORM_INPUT_WEBSITE}
              </Nunito20>
              <InputValidation
                type="url"
                name="website"
                value={formik.website}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.website}
                validationMessage={formik.errors.website}
              />
            </div>

            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>
                {COMPANY_FORM_INPUT_EMPLOYEES_NBR}
              </Nunito20>
              <InputValidation
                type="number"
                name="employeesNbr"
                value={formik.employeesNbr}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.employeesNbr}
                validationMessage={ERROR_REQUIRED}
              />
            </div>
            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>{COMPANY_FORM_INPUT_PHONE}</Nunito20>
              <PhoneInputValidation
                name="phoneNumber"
                value={formik.phoneNumber}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.phoneNumber}
                validationMessage={formik.errors.phoneNumber}
              />
            </div>

            <div style={inputContainer}>
              <Nunito20 style={inputLabel}>
                {COMPANY_FORM_INPUT_EMPLOYEE_ROLE}
              </Nunito20>
              <InputValidation
                type="text"
                name="userRole"
                value={formik.userRole}
                handleInputChange={formik.handleChange}
                hasError={formik.errors.userRole}
                validationMessage={formik.errors.userRole}
              />
            </div>
          </div>
        </div>
        <div style={tickBoxContainer}>
          <div style={checkBoxDiv}>
            <Checkbox handleChange={formik.handleChange} name="personCheck" />
            <NunitoBold18 style={checkBoxLabel}>{PERSON_CHECK}</NunitoBold18>
          </div>
        </div>
      </div>
      <SubmitButton style={submitButton} onClick={handleSubmit}>
        {CONTINUE}
      </SubmitButton>
    </div>
  );
};

Try尝试

Make use of validateOnChange and validateOnBlur props and issue the value of false.使用validateOnChangevalidateOnBlur属性并发出 false 值。

See docs:请参阅文档:

https://jaredpalmer.com/formik/docs/guides/validation#field-level-validation https://jaredpalmer.com/formik/docs/guides/validation#field-level-validation

https://jaredpalmer.com/formik/docs/api/formik#validateonblur-boolean https://jaredpalmer.com/formik/docs/api/formik#validateonblur-boolean

Any further issues, leave a comment..还有什么问题,评论留言。。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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