# Array-Based Validation Structure - Implementation Guide

## ✅ Overview

Both `company-add.php` and `courier-partner-add.php` now use a **clean, array-based validation structure** that makes it easy to add, modify, or remove validation rules.

---

## 🎯 **New Validation Structure**

### Pattern
```javascript
function validateForm() {
    let isValid = true;
    let errors = [];
    
    // Clear previous errors
    $('.is-invalid').removeClass('is-invalid');
    
    // Define validation rules
    let fields = [
        { 
            id: "field_name", 
            message: "Field Name is required.",
            required: true,
            pattern: /regex_pattern/,
            patternMessage: "Custom error message"
        },
        // ... more fields
    ];
    
    // Validate each field
    fields.forEach(function(field) {
        let value = $('#' + field.id).val().trim();
        
        if (field.required && !value) {
            $('#' + field.id).addClass('is-invalid');
            errors.push(field.message);
            isValid = false;
        }
        else if (value && field.pattern && !field.pattern.test(value)) {
            $('#' + field.id).addClass('is-invalid');
            errors.push(field.patternMessage || field.message);
            isValid = false;
        }
    });
    
    if (!isValid) {
        showtoastt(errors[0], 'error');
    }
    
    return isValid;
}
```

---

## 📋 **Company Form Validation**

### Field Definitions
```javascript
let fields = [
    { 
        id: "company_name", 
        message: "Company Name is required.",
        required: true
    },
    { 
        id: "phone_number", 
        message: "Phone Number is required.",
        required: true,
        pattern: /^\d{10}$/,
        patternMessage: "Phone number must be 10 digits"
    },
    { 
        id: "address", 
        message: "Address is required.",
        required: true
    },
    { 
        id: "city", 
        message: "City is required.",
        required: true
    },
    { 
        id: "state", 
        message: "State is required.",
        required: true
    },
    { 
        id: "gst_no", 
        message: "GST No is invalid.",
        required: false,
        pattern: /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/,
        patternMessage: "Invalid GST number format (e.g., 27AAPFU0939F1ZV)"
    },
    { 
        id: "pincode", 
        message: "Pincode is invalid.",
        required: false,
        pattern: /^\d{6}$/,
        patternMessage: "Pincode must be 6 digits"
    }
];
```

---

## 🚚 **Courier Partner Form Validation**

### Field Definitions
```javascript
let fields = [
    { 
        id: "partner_name", 
        message: "Partner Name is required.",
        required: true
    },
    { 
        id: "partner_code", 
        message: "Partner Code is required.",
        required: true,
        pattern: /^[A-Z0-9_]+$/,
        patternMessage: "Partner code must contain only uppercase letters, numbers, and underscores"
    },
    { 
        id: "api_url", 
        message: "API URL is invalid.",
        required: false,
        pattern: /^https?:\/\/.+/,
        patternMessage: "API URL must be a valid URL (http:// or https://)"
    },
    { 
        id: "preference_order", 
        message: "Preference Order is invalid.",
        required: false,
        custom: function(value) {
            return value === '' || (!isNaN(value) && parseInt(value) >= 0);
        },
        patternMessage: "Preference order must be 0 or greater"
    }
];
```

---

## 🔧 **Field Object Properties**

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `id` | String | ✅ Yes | HTML element ID (without #) |
| `message` | String | ✅ Yes | Error message for required field |
| `required` | Boolean | ✅ Yes | Is field required? |
| `pattern` | RegExp | ❌ No | Regex pattern for validation |
| `patternMessage` | String | ❌ No | Error message for pattern mismatch |
| `custom` | Function | ❌ No | Custom validation function |

---

## 📝 **How to Add New Validations**

### Example 1: Add Email Field
```javascript
{ 
    id: "email", 
    message: "Email is required.",
    required: true,
    pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    patternMessage: "Invalid email format"
}
```

### Example 2: Add Optional Website URL
```javascript
{ 
    id: "website", 
    message: "Website URL is invalid.",
    required: false,
    pattern: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b/,
    patternMessage: "Invalid website URL"
}
```

### Example 3: Add Custom Age Validation
```javascript
{ 
    id: "age", 
    message: "Age is required.",
    required: true,
    custom: function(value) {
        let age = parseInt(value);
        return !isNaN(age) && age >= 18 && age <= 100;
    },
    patternMessage: "Age must be between 18 and 100"
}
```

### Example 4: Add Password Strength
```javascript
{ 
    id: "password", 
    message: "Password is required.",
    required: true,
    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
    patternMessage: "Password must be 8+ chars with uppercase, lowercase, number, and special character"
}
```

---

## 🎨 **Validation Types**

### 1. Required Field Only
```javascript
{ 
    id: "field_name", 
    message: "Field Name is required.",
    required: true
}
```

### 2. Optional with Pattern
```javascript
{ 
    id: "field_name", 
    message: "Field Name is invalid.",
    required: false,
    pattern: /pattern/,
    patternMessage: "Custom error"
}
```

### 3. Required with Pattern
```javascript
{ 
    id: "field_name", 
    message: "Field Name is required.",
    required: true,
    pattern: /pattern/,
    patternMessage: "Custom error"
}
```

### 4. Custom Validation Function
```javascript
{ 
    id: "field_name", 
    message: "Field Name is invalid.",
    required: false,
    custom: function(value) {
        // Return true if valid, false if invalid
        return someCondition;
    },
    patternMessage: "Custom error"
}
```

---

## ✨ **Benefits**

### 1. **Easy to Maintain**
- All validation rules in one place
- Add/remove fields easily
- Clear structure

### 2. **Reusable**
- Copy field definitions to other forms
- Consistent validation across app
- DRY principle

### 3. **Readable**
- Self-documenting code
- Clear field requirements
- Easy to understand

### 4. **Flexible**
- Support for regex patterns
- Custom validation functions
- Optional and required fields

### 5. **Scalable**
- Add unlimited fields
- Complex validation logic
- Easy to extend

---

## 🔄 **Migration from Old Structure**

### Before (Old Way)
```javascript
// Scattered validation logic
let phone = $('#phone_number').val().trim();
if (phone && !/^\d{10}$/.test(phone)) {
    $('#phone_number').addClass('is-invalid');
    errors.push('Phone number must be 10 digits');
    isValid = false;
}

let gst = $('#gst_no').val().trim();
if (gst && !/^[0-9]{2}[A-Z]{5}.../.test(gst)) {
    $('#gst_no').addClass('is-invalid');
    errors.push('Invalid GST number format');
    isValid = false;
}
// ... more scattered code
```

### After (New Way)
```javascript
// Centralized validation rules
let fields = [
    { 
        id: "phone_number", 
        message: "Phone Number is required.",
        required: true,
        pattern: /^\d{10}$/,
        patternMessage: "Phone number must be 10 digits"
    },
    { 
        id: "gst_no", 
        message: "GST No is invalid.",
        required: false,
        pattern: /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/,
        patternMessage: "Invalid GST number format"
    }
];

// Single loop handles all validations
fields.forEach(function(field) { /* ... */ });
```

---

## 📚 **Common Patterns**

### Indian Phone Number
```javascript
pattern: /^[6-9]\d{9}$/
```

### Indian Pincode
```javascript
pattern: /^\d{6}$/
```

### GST Number
```javascript
pattern: /^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/
```

### PAN Number
```javascript
pattern: /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/
```

### Aadhaar Number
```javascript
pattern: /^\d{12}$/
```

### IFSC Code
```javascript
pattern: /^[A-Z]{4}0[A-Z0-9]{6}$/
```

### Uppercase Alphanumeric with Underscore
```javascript
pattern: /^[A-Z0-9_]+$/
```

### URL (HTTP/HTTPS)
```javascript
pattern: /^https?:\/\/.+/
```

---

## 🧪 **Testing**

### Test Required Field
```javascript
// Leave field empty and submit
// Expected: "Field Name is required." error
```

### Test Pattern Validation
```javascript
// Enter invalid format and submit
// Expected: Pattern error message
```

### Test Custom Validation
```javascript
// Enter value that fails custom function
// Expected: Custom error message
```

---

**Version**: 2.0  
**Structure**: Array-Based Validation  
**Files**: `company-add.php`, `courier-partner-add.php`  
**Last Updated**: 2026-02-10
