Published on

Validate String or Number Length with Yup

Authors
  • Name
    Ripal & Zalak
    Twitter

Validate String or Number Length with Yup

Yup is a powerful JavaScript schema validation library commonly used with form libraries like Formik. One of its essential features is validating the length of strings or numbers. This article dives deep into length validation, complete with practical examples, scenarios, FAQs, and tips for SEO optimization.

Why Validate Length with Yup?

Validating length is critical for ensuring input correctness. Common use cases include:

  • ZIP Codes: Must be exactly 5 digits.
  • Phone Numbers: Length varies by country but is strictly defined.
  • Passwords: Often require minimum and maximum lengths.
  • Usernames: Length constraints to ensure readability and uniqueness.

By using Yup, you ensure clean, maintainable validation rules with minimal boilerplate.


Scenarios and Examples

1. Validating Exact Length

To validate that a string has an exact length, use the .length() method:

import * as Yup from 'yup'

const schema = Yup.object().shape({
  username: Yup.string()
    .length(8, 'Username must be exactly 8 characters')
    .required('Username is required'),
})

Scenario:

Use Case: Validating usernames in an application where the system requires exactly 8 characters.

schema.validateSync({ username: 'abcd1234' }) // Pass
schema.validateSync({ username: 'abc123' }) // Fail: Username must be exactly 8 characters

2. Validating Minimum and Maximum Lengths

Use .min() and .max() for length ranges:

const schema = Yup.object().shape({
  password: Yup.string()
    .min(6, 'Password must be at least 6 characters')
    .max(20, 'Password cannot exceed 20 characters')
    .required('Password is required'),
})

Scenario:

Use Case: Validating passwords to meet security requirements.

schema.validateSync({ password: 'secret' }) // Pass
schema.validateSync({ password: 'short' }) // Fail: Must be at least 6 characters
schema.validateSync({ password: 'thispasswordistoolong' }) // Fail: Cannot exceed 20 characters

3. Validating Numeric Inputs as Strings

const schema = Yup.object().shape({
  zipCode: Yup.string()
    .matches(/^\d{5}$/, 'ZIP code must be exactly 5 digits')
    .required('ZIP code is required'),
})

Scenario:

Use Case: Validating ZIP codes in the United States.

schema.validateSync({ zipCode: '12345' }) // Pass
schema.validateSync({ zipCode: '123' }) // Fail: Must be exactly 5 digits
schema.validateSync({ zipCode: '123ab' }) // Fail: Must be digits only

4. Validating Numbers

If numbers are required, you can use .test() to validate their length:

const schema = Yup.object().shape({
  phoneNumber: Yup.number()
    .test(
      'len',
      'Phone number must be exactly 10 digits',
      (value) => value && value.toString().length === 10
    )
    .required('Phone number is required'),
})

Scenario:

Use Case: Validating phone numbers to ensure they contain exactly 10 digits.

schema.validateSync({ phoneNumber: 1234567890 }) // Pass
schema.validateSync({ phoneNumber: 12345 }) // Fail: Must be exactly 10 digits

5. Advanced Validation Using Custom Regex

const schema = Yup.object().shape({
  postalCode: Yup.string()
    .matches(/^\d{5}(?:-\d{4})?$/, 'Invalid postal code format')
    .required('Postal code is required'),
})

Scenario:

Use Case: Validating U.S. postal codes that may include an optional 4-digit suffix.

schema.validateSync({ postalCode: '12345' }) // Pass
schema.validateSync({ postalCode: '12345-6789' }) // Pass
schema.validateSync({ postalCode: '1234' }) // Fail: Invalid format

FAQs

1. Can I validate numbers starting with zeros?

Yes, but treat them as strings to preserve the leading zeros. For example:

Yup.string()
  .matches(/^\d{5}$/, 'Must be exactly 5 digits')
  .required('ZIP code is required')

2. How do .min(), .max(), and .length() differ?

  • .length(): Enforces an exact length.
  • .min(): Specifies a minimum length.
  • .max(): Specifies a maximum length.

3. What happens if a field is null or undefined?

Add .nullable() or .notRequired() to handle such cases without errors.

4. Can I use Yup for validating arrays?

Yes, use .array().of() to define schemas for array items.

5. How do I validate dynamic fields?

Use Yup.lazy() to create dynamic validation rules based on runtime values.

6. What’s the best way to validate passwords?

Combine .min(), .max(), and .matches() for strength requirements. Example:

Yup.string()
  .min(8, 'Password must be at least 8 characters')
  .matches(/[A-Z]/, 'Must contain an uppercase letter')
  .matches(/[0-9]/, 'Must contain a number')
  .required('Password is required')

By mastering Yup’s validation methods, you can ensure accurate, user-friendly input handling for your forms. Explore the Yup documentation for more advanced use cases.