Yup String Validation: The Complete Guide


Validating text inputs is one of the most common needs in web forms and APIs. Whether you’re handling usernames, passwords, emails, or formatted strings like phone numbers and dates, ensuring correct input is essential for both data integrity and user experience.

Yup string validation makes this process simple and powerful by letting you define flexible rules with methods such as .min(), .max(), .matches(), .trim(), and more.

In this guide, we’ll explore how to define and validate Yup strings across different real-world scenarios—covering basics like required fields, advanced use cases such as regex patterns and enums, and even error handling. By the end, you’ll know exactly how to create robust validation rules for text fields in forms, APIs, or TypeScript-based projects.

If you’re just starting with Yup, this is your step-by-step resource to master string schema validation—so you can build reliable, user-friendly applications.

Defining a Yup String

Yup lets you define strings using the .string() method. This tells Yup that the field must always be of type string, and then you can chain additional methods to apply rules such as length limits, patterns, or transformations. This makes it straightforward to validate text inputs like names, emails, or identifiers.

const usernameSchema = yup.string().strict();

Explanation:

  • yup.string() → starts a string schema.
  • No additional rules are applied yet, so any string is valid (including an empty string by default).

This definition means "hello" or "123" will pass, but values like 42, true, or null will fail because they are not strings.

Validating a Yup String

Once you’ve defined a string schema, the next step is to validate actual input data against it. Yup provides the .validate() method, which checks the value and either returns the validated string or throws detailed error messages.

const usernameSchema = yup.string().min(3).required("Username is required");

try {
  const result = await usernameSchema.validate("ab");
  console.log("Valid data:", result);
} catch (err) {
  if (err instanceof yup.ValidationError) {
    console.log("Validation failed:", err.errors);
  }
}

Explanation:

  • .validate("ab") → checks the input string against the schema.
  • The string "ab" fails because it does not meet the .min(3) rule.
  • Yup throws a ValidationError, and the error message is logged in the console.
  • If you pass "sharu", the schema succeeds, and the validated string is returned.

Different Scenarios in Yup Strings

Yup strings can be customized for a wide variety of use cases. From basic text fields like usernames and passwords to advanced formats such as emails, URLs, and UUIDs, you can combine string methods with other Yup features to handle almost any validation scenario.

Basic String Constraints in Yup

const basicStringSchema = yup.string()
  .required("This field is required") // cannot be empty
  .nullable() // allows null values
  .ensure(); // converts null to empty string

Explanation: This schema enforces a string input while covering different cases:

  • .required() makes the field mandatory.
  • .nullable() allows null values if the input is missing.
  • .ensure() transforms null into an empty string automatically.

This setup helps with forms where empty strings, nulls, or optional values need to be handled consistently.

String Length Rules in Yup

const lengthSchema = yup.string()
  .min(3, "Minimum 3 characters required")
  .max(10, "Maximum 10 characters allowed")
  .length(5, "Must be exactly 5 characters long");

Explanation:

  • .min() → ensures a minimum number of characters.
  • .max() → restricts the maximum characters.
  • .length() → enforces exact string length.

Perfect for cases like passwords, usernames, or codes that need strict character limits.

Pattern & Regex Validations in Yup

const patternSchema = yup.string()
  .matches(/^[a-zA-Z]+$/, "Only letters are allowed")
  .matches(/^[0-9]+$/, "Only numbers are allowed")
  .matches(/^[a-zA-Z0-9]+$/, "Must be alphanumeric")
  .matches(/^\S*$/, "No spaces allowed")
  .matches(/hello/, "Must contain the word 'hello'");

Explanation:
.matches(regex, message) gives you full regex power.

  • You can validate letters only, numeric-only, alphanumeric, or forbid spaces.
  • .contains() isn’t a Yup method, but you can replicate it using .matches() with a substring pattern.

Transformations & Formatting in Yup

const transformSchema = yup.string()
  .trim() // removes extra spaces
  .lowercase() // converts input to lowercase
  .transform((val) => val?.split(" ")[0]); // keep only first word

Explanation:

  • .trim() ensures no leading/trailing spaces.
  • .lowercase() makes input consistent.
  • .transform() customizes strings (like splitting text, applying default formatting, or extracting values).

This is useful for normalizing user input before saving or validating.

Special String Types in Yup

const specialSchema = yup.object({
  email: yup.string().email("Invalid email address"),
  website: yup.string().url("Invalid URL"),
  phone: yup.string().matches(/^\+?[0-9]{10,15}$/, "Invalid phone number"),
  password: yup.string().min(8).matches(/[A-Z]/, "Must contain an uppercase letter"),
  date: yup.string().matches(/^\d{4}-\d{2}-\d{2}$/, "Must be YYYY-MM-DD format"),
});

Explanation:
Yup includes built-in email and url validators.
For others (phone, password, date format, datetime), regex patterns are used.

String Enum, OneOf & Equality in Yup

const enumSchema = yup.string()
  .oneOf(["admin", "editor", "viewer"], "Invalid role");

const equalsSchema = yup.string().strict()
  .test("equals", "Must equal 'tecktol'", (val) => val === "tecktol");

Explanation:

  • .oneOf() restricts values to a predefined set (like enums).
  • .mixed() handles cases where input may be string, number, null, etc.
  • Custom .test() allows direct comparison with exact values.

Default Values & Optional Cases in Yup

const defaultSchema = yup.string()
  .default("Guest") // fallback if not provided
  .test("not-whitespace", "Cannot be only spaces", (val) => val?.trim().length > 0);

Explanation:

  • .default() assigns a fallback.
  • Custom .test() avoids pure whitespace strings.
  • .optional() is implicit in Yup when .required() is not applied.

Error Handling in Yup Strings

When validating strings, Yup can return one or multiple error messages depending on the configuration. By default, Yup stops at the first error (abortEarly: true).

If you want to capture all validation issues in a single run, you can set abortEarly: false. This is especially useful when you want to display multiple error messages to the user at once.

const passwordSchema = yup
  .string()
  .required("Password is required")
  .min(8, "Password must be at least 8 characters long")
  .matches(/[A-Z]/, "Password must contain at least one uppercase letter")
  .matches(/[0-9]/, "Password must contain at least one number");

try {
  await passwordSchema.validate("abc", { abortEarly: false });
} catch (err) {
  if (err instanceof yup.ValidationError) {
    console.log("Validation errors:");
    err.errors.forEach((message) => console.log("-", message));
  }
}

Explanation:

  • .required("Password is required") → ensures the field is not empty.
  • .min(8) → enforces a minimum length of 8 characters.
  • .matches(/[A-Z]/) → requires at least one uppercase letter.
  • .matches(/[0-9]/) → requires at least one number.

Input "abc" fails three checks:

  1. Too short (less than 8 characters).
  2. Does not contain an uppercase letter.
  3. Does not contain a number.

Because abortEarly: false is used, Yup reports all validation errors together instead of stopping at the first failure.

Conclusion

Yup string schemas give you precise control over text validation, from the simplest required field to complex scenarios like enforcing passwords, URLs, or custom patterns. By combining methods such as .required(), .nullable(), .min(), .matches(), .oneOf(), and .transform(), you can tailor your validation logic to fit any form or API requirement.

With proper error handling (like using { abortEarly: false }), you can also provide clear, user-friendly feedback, making your forms much more reliable and accessible.

Mastering Yup string validation not only improves the quality of your input handling but also lays the foundation for scaling into more complex schemas involving arrays, objects, and mixed data types.

Start applying these string validation techniques today to make your applications cleaner, safer, and more user-focused.

For a deeper look at validating arrays, objects, and mixed types, check our full Yup schema reference

Sharukhan Avatar

Sharukhan Patan

Sharukhan Patan is the founder of Tecktol. He has worked as a software engineer specializing in full-stack web development.

Popular Posts