Course contentsShow
← React
Lesson 1238 of 2,39631. Forms in ReactFree lesson

Common Validation Rules: String Constraints

Applying email, url, min, max, regex, and other built-in string validations to form fields.

Common Validation Rules: String Constraints

What you'll learn: How to apply Zod's built-in string validation methods to enforce email formats, URLs, length limits, and custom patterns in your forms.

The Problem: Strings Need Boundaries

When validating user input, plain z.string() only checks that a value is a string—it doesn't enforce format rules. Real forms need constraints: "Must be an email," "No more than 50 characters," "Must match this pattern."

Built-In String Validators

Zod provides chainable methods for common string requirements:

import { z } from 'zod';

const schema = z.object({
  // Email validation
  email: z.string().email('Invalid email address'),
  
  // URL validation
  website: z.string().url('Must be a valid URL'),
  
  // Length constraints
  username: z.string()
    .min(3, 'Username must be at least 3 characters')
    .max(20, 'Username cannot exceed 20 characters'),
  
  // Exact length
  zipCode: z.string().length(5, 'ZIP code must be exactly 5 digits'),
  
  // Regex pattern
  phoneNumber: z.string().regex(
    /^\d{3}-\d{3}-\d{4}$/,
    'Phone must be format: 123-456-7890'
  ),
  
  // UUID validation
  userId: z.string().uuid('Invalid user ID format'),
});

Think of It Like a Checklist

Each constraint method adds another gate your string must pass through. z.string().email().min(5) means: "Must be a string, and a valid email format, and at least 5 characters."

The custom error messages (second argument) replace Zod's defaults, making your form errors user-friendly.

Common Patterns

  • Email fields: Always use .email()
  • URLs: Use .url() for website inputs
  • Usernames: Combine .min() and .max()
  • Special formats: Use .regex() for phone numbers, postal codes, etc.

Key Takeaway: Zod's string constraint methods (.email(), .url(), .min(), .max(), .regex()) let you declaratively enforce format rules without writing custom validation logic—and they integrate seamlessly with React Hook Form via resolvers.