James
James

Reputation: 2860

Formik with Yup allows valid validation when empty strings are given

I have a form within a React app that uses Formik with You for validation. The validation is working as expected apart from a user can enter a string with one or more whitespace into the fields and this will allow the validation to pass and the form to be submitted. I cannot see an obvious way to ensure that the string entered into each field is not an empty string containing whitespace ( " " ).

Here is my code:

const formik = useFormik<yup.InferType<typeof validationSchema>>({
    initialValues: {
      addressLine1: portfolioState.clientAddress.addressLine1,
      addressLine2: portfolioState.clientAddress.addressLine2,
      postcode: portfolioState.clientAddress.postcode,
      cityOrTownName: portfolioState.clientAddress.cityOrTownName,
      county: portfolioState.clientAddress.county,
      country: countryByLocale[onboardingState.settingsState.locale],
    },

    onSubmit: async () => {
      console.log(Object.entries(formik.values));
      const { createdDate, lastModifiedDate, postcode, ...rest } = portfolioState.clientAddress;
      const addressUpdatePayload = {
        ...rest,
        ...formik.values,
        addressType: AddressTypeEnum.INVOICE,
      };
      ...       

    },
    validationSchema,
  });

    <FormWrapper>
          <Form onSubmit={formik.handleSubmit}>
            <Form.Group style={styles.formGroupStyle}>
              <Form.Label className="required">{t('auth:addressLine1.label')}</Form.Label>
              <Form.Control
                type="text"
                maxLength={30}
                name="addressLine1"
                onChange={formik.handleChange}
                value={formik.values.addressLine1}
                isValid={formik.touched.addressLine1 && !formik.errors.addressLine1}
                isInvalid={Boolean(formik.errors.addressLine1)}
              />
              <span style={styles.subText}>{t('auth:addressLine1.subText')}</span>
            </Form.Group>

            <Form.Group style={styles.formGroupStyle}>
              <Form.Label>{t('auth:addressLine2.label')}</Form.Label>
              <Form.Control
                type="text"
                maxLength={30}
                name="addressLine2"
                onChange={formik.handleChange}
                value={formik.values.addressLine2}
                isValid={formik.touched.addressLine2 && !formik.errors.addressLine2}
                isInvalid={Boolean(formik.errors.addressLine2)}
              />
              <span style={styles.subText}>{t('auth:addressLine2.subText')}</span>
            </Form.Group>

            <Form.Group style={{ ...styles.formGroupStyle, ...styles.flexFormGroup }}>
              <div style={{ marginRight: 15 }}>
                <Form.Label className="required" style={{ whiteSpace: 'nowrap' }}>
                  {showUkInputs ? t('auth:postcode.label') : t('auth:zipCode.label')}
                </Form.Label>
                <Form.Control
                  type="text"
                  name="postcode"
                  maxLength={7}
                  onChange={formik.handleChange}
                  value={formik.values.postcode}
                  isValid={formik.touched.postcode && !formik.errors.postcode}
                  isInvalid={Boolean(formik.errors.postcode)}
                />
              </div>

              <div>
                <Form.Label className="required">{t('auth:cityOrTownName.label')}</Form.Label>
                <Form.Control
                  type="text"
                  name="cityOrTownName"
                  onChange={formik.handleChange}
                  value={formik.values.cityOrTownName}
                  isValid={formik.touched.cityOrTownName && !formik.errors.cityOrTownName}
                  isInvalid={Boolean(formik.errors.cityOrTownName)}
                />
              </div>

              <div style={{ marginLeft: 15 }}>
                <Form.Label>{showUkInputs ? t('auth:county.label') : t('auth:state.label')}</Form.Label>
                <Form.Control
                  type="string"
                  name="county"
                  onChange={formik.handleChange}
                  value={formik.values.county}
                  isValid={formik.touched.county && !formik.errors.county}
                  isInvalid={Boolean(formik.errors.county)}
                />
              </div>
            </Form.Group>

            <Form.Group style={styles.formGroupStyle}>
              <Form.Label>{t('auth:country.label')}</Form.Label>

              <Form.Control
                name="country"
                as="select"
                value={formik.values.country}
                onChange={handleCountryChange()}
                style={styles.countrySelect}
                isValid={!formik.errors.country}
              >
                {countriesList.map((item: ICountrySelectValue) => (
                  <option
                    aria-selected="true"
                    key={item.key}
                    value={item.value}
                    selected={item.value === portfolioState.userDetails.country}
                  >
                    {item.key}
                  </option>
                ))}
              </Form.Control>
            </Form.Group>
            <Button
              id="billing-address-submit"
              type="submit"
              style={{
                ...{ backgroundColor: GlobalStyles.cultOrange, color: 'black', marginTop: 30 },
                ...(styles.buttonStyle as React.CSSProperties),
              }}
              disabled={onboardingState.uiState.allowContinue === false || formik.isSubmitting || !formik.isValid}
            >
              {t('common:continue')}
            </Button>
          </Form>
        </FormWrapper>

Can anyone offer any advice? thanks

Upvotes: 2

Views: 1778

Answers (1)

Saheed Adewale Shittu
Saheed Adewale Shittu

Reputation: 31

To prevent a user from entering empty strings in the text input field, you can use the .trim() method in the validation. Here is the link to the documentation. [1]: https://github.com/jquense/yup#stringtrimmessage-string--function-schema

Upvotes: 3

Related Questions