Step 4: Validation Rules
Validation Rules ensure that the data submitted to your API meets your requirements and business logic. This step configures field validation, business rules, and error handling.
Overview
The Validation Rules step allows you to:
Set up field-level validation
Configure business logic validation
Define custom validation rules
Handle errors and provide user feedback
Field Validation
Text Field Validation
Length Validation
// Minimum and maximum length
{
"field": "name",
"type": "string",
"validation": {
"minLength": 2,
"maxLength": 50,
"errorMessage": "Name must be between 2 and 50 characters"
}
}Format Validation
// Email format validation
{
"field": "email",
"type": "string",
"validation": {
"format": "email",
"errorMessage": "Please enter a valid email address"
}
}
// Phone number validation
{
"field": "phone",
"type": "string",
"validation": {
"format": "phone",
"pattern": "^\\+?[1-9]\\d{1,14}$",
"errorMessage": "Please enter a valid phone number"
}
}
// URL validation
{
"field": "website",
"type": "string",
"validation": {
"format": "url",
"errorMessage": "Please enter a valid URL"
}
}Custom Pattern Validation
// Custom regex pattern
{
"field": "username",
"type": "string",
"validation": {
"pattern": "^[a-zA-Z0-9_]{3,20}$",
"errorMessage": "Username must be 3-20 characters, letters, numbers, and underscores only"
}
}
// Password strength validation
{
"field": "password",
"type": "string",
"validation": {
"pattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$",
"errorMessage": "Password must be at least 8 characters with uppercase, lowercase, number, and special character"
}
}Number Field Validation
Range Validation
// Age validation
{
"field": "age",
"type": "number",
"validation": {
"min": 18,
"max": 120,
"errorMessage": "Age must be between 18 and 120"
}
}
// Rating validation
{
"field": "rating",
"type": "number",
"validation": {
"min": 1,
"max": 5,
"integer": true,
"errorMessage": "Rating must be between 1 and 5"
}
}Decimal Validation
// Price validation
{
"field": "price",
"type": "number",
"validation": {
"min": 0,
"max": 999999.99,
"decimalPlaces": 2,
"errorMessage": "Price must be between $0.00 and $999,999.99"
}
}Select Field Validation
Option Validation
// Single select validation
{
"field": "category",
"type": "string",
"validation": {
"options": ["General", "Support", "Sales", "Other"],
"errorMessage": "Please select a valid category"
}
}
// Multiple select validation
{
"field": "interests",
"type": "array",
"validation": {
"options": ["Technology", "Sports", "Music", "Travel", "Food"],
"minSelections": 1,
"maxSelections": 3,
"errorMessage": "Please select 1-3 interests"
}
}Date Field Validation
Date Range Validation
// Event date validation
{
"field": "event_date",
"type": "date",
"validation": {
"minDate": "today",
"maxDate": "+1year",
"errorMessage": "Event date must be between today and one year from now"
}
}
// Birth date validation
{
"field": "birth_date",
"type": "date",
"validation": {
"maxDate": "18yearsago",
"errorMessage": "You must be at least 18 years old"
}
}Business Logic Validation
Cross-Field Validation
Conditional Requirements
// If rating is 5, feedback is required
{
"rule": "conditional_required",
"condition": {
"field": "rating",
"operator": "equals",
"value": 5
},
"requiredFields": ["feedback"],
"errorMessage": "Feedback is required for 5-star ratings"
}
// If event type is paid, payment method is required
{
"rule": "conditional_required",
"condition": {
"field": "event_type",
"operator": "equals",
"value": "paid"
},
"requiredFields": ["payment_method"],
"errorMessage": "Payment method is required for paid events"
}Value Dependencies
// End date must be after start date
{
"rule": "date_comparison",
"fields": ["start_date", "end_date"],
"operator": "after",
"errorMessage": "End date must be after start date"
}
// Age must match birth date
{
"rule": "age_validation",
"fields": ["age", "birth_date"],
"errorMessage": "Age must match birth date"
}Calculation Validation
// Total must equal sum of items
{
"rule": "calculation",
"fields": ["item1", "item2", "item3", "total"],
"formula": "item1 + item2 + item3 = total",
"errorMessage": "Total does not match sum of items"
}Custom Validation Rules
JavaScript Functions
// Custom business rule
{
"rule": "custom_function",
"function": "validateBusinessHours",
"parameters": ["submission_time"],
"errorMessage": "Submissions are only accepted during business hours (9 AM - 5 PM)"
}
// Function implementation
function validateBusinessHours(submissionTime) {
const hour = new Date(submissionTime).getHours();
return hour >= 9 && hour <= 17;
}External API Validation
// Validate against external service
{
"rule": "external_validation",
"service": "email_verification",
"field": "email",
"errorMessage": "Email address could not be verified"
}
// Validate postal code
{
"rule": "external_validation",
"service": "postal_code_validation",
"fields": ["postal_code", "country"],
"errorMessage": "Invalid postal code for the selected country"
}Database Lookups
// Check if email already exists
{
"rule": "unique_check",
"field": "email",
"table": "users",
"errorMessage": "Email address is already registered"
}
// Validate product ID exists
{
"rule": "exists_check",
"field": "product_id",
"table": "products",
"errorMessage": "Product ID does not exist"
}Error Handling
Error Message Configuration
Field-Specific Messages
{
"field": "email",
"validation": {
"format": "email",
"errorMessage": "Please enter a valid email address",
"errorCode": "INVALID_EMAIL"
}
}Context-Aware Messages
{
"field": "age",
"validation": {
"min": 18,
"errorMessage": "You must be at least 18 years old to register",
"errorCode": "AGE_TOO_YOUNG",
"suggestion": "Please verify your birth date"
}
}Localized Messages
{
"field": "name",
"validation": {
"required": true,
"errorMessages": {
"en": "Name is required",
"es": "El nombre es obligatorio",
"fr": "Le nom est requis"
}
}
}Error Response Format
Single Field Error
{
"success": false,
"errors": [
{
"field": "email",
"message": "Please enter a valid email address",
"code": "INVALID_EMAIL",
"value": "invalid-email"
}
]
}Multiple Field Errors
{
"success": false,
"errors": [
{
"field": "name",
"message": "Name is required",
"code": "REQUIRED_FIELD",
"value": ""
},
{
"field": "email",
"message": "Please enter a valid email address",
"code": "INVALID_EMAIL",
"value": "invalid-email"
},
{
"field": "age",
"message": "Age must be between 18 and 120",
"code": "INVALID_RANGE",
"value": 15
}
]
}Business Logic Error
{
"success": false,
"errors": [
{
"rule": "conditional_required",
"message": "Feedback is required for 5-star ratings",
"code": "CONDITIONAL_REQUIRED",
"fields": ["feedback"],
"condition": {
"field": "rating",
"value": 5
}
}
]
}Validation Testing
Test Cases
Valid Data
{
"name": "John Doe",
"email": "john@example.com",
"age": 25,
"rating": 4,
"feedback": "Great service!"
}Invalid Data
{
"name": "",
"email": "invalid-email",
"age": 15,
"rating": 6,
"feedback": ""
}Edge Cases
{
"name": "A",
"email": "a@b.c",
"age": 0,
"rating": 1,
"feedback": "x".repeat(1000)
}Testing Checklist
[ ] Required field validation
[ ] Format validation (email, phone, URL)
[ ] Length validation (min/max)
[ ] Range validation (numbers, dates)
[ ] Option validation (select fields)
[ ] Cross-field validation
[ ] Custom business rules
[ ] Error message accuracy
[ ] Error response format
[ ] Edge case handling
Performance Considerations
Validation Optimization
Early Validation
Validate required fields first
Check format before complex validation
Use efficient validation order
Caching
Cache validation results
Store validation rules in memory
Optimize database lookups
Async Validation
Use async validation for external services
Implement timeout handling
Provide fallback validation
Security Considerations
Input Sanitization
// Sanitize text input
{
"field": "message",
"validation": {
"sanitize": true,
"removeHtml": true,
"maxLength": 1000
}
}SQL Injection Prevention
// Use parameterized queries
{
"rule": "database_lookup",
"query": "SELECT * FROM users WHERE email = ?",
"parameters": ["email"]
}XSS Prevention
// Escape HTML characters
{
"field": "content",
"validation": {
"escapeHtml": true,
"allowedTags": ["b", "i", "em", "strong"]
}
}Next Steps
After configuring validation rules:
- Set Up Response Configuration → Step 5: Response Configuration
- Test and Deploy → Step 6: Testing & Deployment
Related Topics
Field Configuration - Setting up API fields
Form Integration - Connecting forms to your API
API Reference - Complete API documentation