yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required:

import * as Yup from "yup";

const validationSchema = Yup.object().shape({
  firstField: Yup.string().matches(/^[A-Za-z]*$/, {
    message: "First field must contain only alphabetic characters",
    excludeEmptyString: true,
  }),
  secondField: Yup.string().when("firstField", {
    is: (value) => value && value.length > 0,
    then: Yup.string().required(
      "Second field is required when first field is filled"
    ),
  }),
});

export default validationSchema;

In the updated code, we’re using the matches method from Yup to enforce that the firstField must contain only alphabetic characters. The regular expression checks if the string consists only of uppercase and lowercase letters. The excludeEmptyString option is set to true to ensure that an empty string is not considered a valid value for the first field.

If the firstField is filled, the secondField is still required using the when method. This means that the second input field will be required only when the first input field is filled, and it will not be required if the first field is left empty.

By implementing this validation logic, you can have an optional first input field that, if filled, must contain only alphabetic characters, and a second input field that is required when the first field is filled.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
How to set up auto-fix on save by using the project’s Eslint config with VS Code

This is a quick instruction to set up auto-fix on save by using the project’s eslint config with VS Code. It works for both TS and JS. 1. Install ESLint plugin for VS Code. 2. Add config to VS code Go to Code -> Preference -> Settings (or press cmd …