> ## Documentation Index
> Fetch the complete documentation index at: https://developer.kodexa.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Adding Validation Rules

> Apply different validation rules based on document characteristics in Kodexa, conditionally adding fields and approval requirements to extractions.

This guide shows how to apply different validation rules based on document characteristics. For example, invoices from certain vendors might require additional approval fields, or documents above a threshold might need extra verification.

## The Goal

Apply conditional validation:

* **High-value invoices** (over \$10,000) require manager approval field
* **International vendors** require additional tax documentation fields
* **Rush orders** skip certain optional validations

## What You'll Create

```mermaid theme={null}
flowchart TD
    subgraph features["Document Features"]
        F1[Feature: "High Value"<br/>amount > $10K]
        F2[Feature: "International Vendor"]
        F3[Feature: "Rush Order"]
    end

    subgraph items["Validation Rules"]
        I1[Item: "Require Manager Approval"]
        I2[Item: "Require Tax Docs"]
        I3[Item: "Skip Optional Fields"]
    end

    subgraph sets["Knowledge Sets"]
        KS1[Set: High Value Rules]
        KS2[Set: International Rules]
        KS3[Set: Rush Order Rules]
    end

    F1 --> KS1 --> I1
    F2 --> KS2 --> I2
    F3 --> KS3 --> I3
```

## Step 1: Create Feature Types

### Invoice Value Tier

```yaml theme={null}
# kodexa-resources/knowledge-feature-types/invoice-value-tier.yaml
slug: invoice-value-tier
name: Invoice Value Tier
description: Categorization of invoices by total value

options:
  - name: tier
    type: string
    label: Value Tier
    description: The value tier (standard, high, critical)
    required: true

extendedOptions:
  - name: thresholdMin
    type: number
    label: Minimum Threshold
  - name: thresholdMax
    type: number
    label: Maximum Threshold
```

### Vendor Location

```yaml theme={null}
# kodexa-resources/knowledge-feature-types/vendor-location.yaml
slug: vendor-location
name: Vendor Location
description: Geographic classification of vendor

options:
  - name: locationType
    type: string
    label: Location Type
    description: domestic or international
    required: true

extendedOptions:
  - name: country
    type: string
    label: Country
  - name: region
    type: string
    label: Region
```

### Processing Priority

```yaml theme={null}
# kodexa-resources/knowledge-feature-types/processing-priority.yaml
slug: processing-priority
name: Processing Priority
description: Processing priority level

options:
  - name: priority
    type: string
    label: Priority
    description: standard, expedited, rush
    required: true
```

## Step 2: Create the Validation Item Type

```yaml theme={null}
# kodexa-resources/knowledge-item-types/validation-rule.yaml
slug: validation-rule
name: Validation Rule
description: Define validation requirements for extracted data

options:
  - name: ruleType
    type: select
    label: Rule Type
    required: true
    options:
      - value: require-field
        label: Require Field
      - value: skip-field
        label: Skip Field Validation
      - value: require-value-range
        label: Require Value in Range
      - value: require-approval
        label: Require Approval

  - name: targetField
    type: string
    label: Target Field
    description: The taxon path this rule applies to
    required: true

  - name: condition
    type: string
    label: Condition Expression
    description: Optional condition for when rule applies

  - name: errorMessage
    type: string
    label: Error Message
    description: Message shown when validation fails

  - name: severity
    type: select
    label: Severity
    options:
      - value: error
        label: Error (blocks processing)
      - value: warning
        label: Warning (allows override)
      - value: info
        label: Info (notification only)
    default: error
```

## Step 3: Create Knowledge Items

### High-Value Invoice Rules

```yaml theme={null}
# Require manager approval for high-value invoices
title: Require Manager Approval
description: High-value invoices must have manager approval
knowledgeItemType: validation-rule
active: true
properties:
  ruleType: require-approval
  targetField: "approval/manager_signature"
  errorMessage: "Invoices over $10,000 require manager approval"
  severity: error
```

```yaml theme={null}
# Require cost center for high-value invoices
title: Require Cost Center
description: High-value invoices must specify cost center
knowledgeItemType: validation-rule
active: true
properties:
  ruleType: require-field
  targetField: "accounting/cost_center"
  errorMessage: "Cost center is required for invoices over $10,000"
  severity: error
```

### International Vendor Rules

```yaml theme={null}
# Require tax documentation for international vendors
title: Require International Tax Documentation
description: International vendors require W-8BEN or equivalent
knowledgeItemType: validation-rule
active: true
properties:
  ruleType: require-field
  targetField: "vendor/tax_documentation_type"
  errorMessage: "International vendors require tax documentation (W-8BEN, W-8BEN-E, etc.)"
  severity: error
```

```yaml theme={null}
# Require wire transfer details for international
title: Require Wire Transfer Details
description: International payments require wire transfer information
knowledgeItemType: validation-rule
active: true
properties:
  ruleType: require-field
  targetField: "payment/wire_transfer_info"
  errorMessage: "Wire transfer details required for international vendors"
  severity: warning
```

### Rush Order Rules

```yaml theme={null}
# Skip optional fields for rush orders
title: Skip Optional Field Validation
description: Rush orders can skip optional documentation
knowledgeItemType: validation-rule
active: true
properties:
  ruleType: skip-field
  targetField: "documentation/supporting_quotes"
  condition: "processing.priority == 'rush'"
  severity: info
```

## Step 4: Create Knowledge Sets

### High-Value Invoice Set

```yaml theme={null}
name: High-Value Invoice Validation
description: Additional validation for invoices over $10,000
status: ACTIVE

features:
  - featureTypeSlug: invoice-value-tier
    properties:
      tier: "high"

items:
  - itemSlug: require-manager-approval
  - itemSlug: require-cost-center
```

### International Vendor Set

```yaml theme={null}
name: International Vendor Validation
description: Validation rules for international vendors
status: ACTIVE

features:
  - featureTypeSlug: vendor-location
    properties:
      locationType: "international"

items:
  - itemSlug: require-international-tax-documentation
  - itemSlug: require-wire-transfer-details
```

### Rush Order Set

```yaml theme={null}
name: Rush Order Processing
description: Relaxed validation for rush orders
status: ACTIVE

features:
  - featureTypeSlug: processing-priority
    properties:
      priority: "rush"

items:
  - itemSlug: skip-optional-field-validation
```

## Combining Multiple Features

Knowledge Sets can require multiple features. For example, high-value international invoices might need extra scrutiny:

```yaml theme={null}
name: High-Value International Invoice Validation
description: Enhanced validation for high-value international invoices
status: ACTIVE

# Both features must be present
features:
  - featureTypeSlug: invoice-value-tier
    properties:
      tier: "high"
  - featureTypeSlug: vendor-location
    properties:
      locationType: "international"

items:
  - itemSlug: require-manager-approval
  - itemSlug: require-international-tax-documentation
  - itemSlug: require-compliance-review  # Additional item for this combination
```

## How Validation Works at Runtime

```mermaid theme={null}
sequenceDiagram
    participant Doc as Document
    participant Proc as Processor
    participant KS as Knowledge System
    participant Val as Validator

    Doc->>Proc: Invoice processed
    Proc->>Doc: Assign features based on content
    Note over Doc: Features: high-value, international

    Proc->>KS: Query matching Knowledge Sets
    KS-->>Proc: Returns matching sets

    Proc->>KS: Get validation items
    KS-->>Proc: Returns validation rules

    Proc->>Val: Apply validation rules
    Val-->>Proc: Validation results

    alt Validation Passed
        Proc->>Doc: Mark as validated
    else Validation Failed
        Proc->>Doc: Create exceptions
    end
```

## Viewing Validation Results

When validation rules are applied:

1. **Passed validations** - Document proceeds to next step
2. **Failed validations (error)** - Document is flagged with exceptions
3. **Failed validations (warning)** - Document can proceed with manual override
4. **Informational** - Notifications logged but processing continues

View applied knowledge and validation results in:

* Document details panel
* Exceptions list
* Workflow search (filter by validation status)

## Best Practices

### 1. Use Appropriate Severity Levels

* **Error**: Critical business rules that must be met
* **Warning**: Important but can be overridden with justification
* **Info**: Nice-to-have or informational checks

### 2. Write Clear Error Messages

```yaml theme={null}
# Good
errorMessage: "Invoices over $10,000 require manager approval. Please upload signed approval form."

# Too vague
errorMessage: "Validation failed"
```

### 3. Document Your Rules

Use the description field to explain the business reason:

```yaml theme={null}
title: Require Tax Documentation
description: |
  IRS requires W-8BEN or W-8BEN-E for payments to non-US vendors.
  This ensures compliance with tax withholding requirements.
  Reference: IRS Publication 515
```

### 4. Test with Pending Review Status

Create Knowledge Sets with `status: PENDING_REVIEW` first to test without affecting production:

```yaml theme={null}
name: New Validation Rule (Testing)
status: PENDING_REVIEW  # Won't apply until activated
```

## Next Steps

* [Knowledge Feature Types](/concepts/knowledge_feature_types) - Full reference
* [Knowledge Item Types](/concepts/knowledge_item_types) - Full reference
* [Customizing Extraction](/concepts/customizing_extraction) - Another common use case
* [Knowledge and Agents](/concepts/knowledge_and_agents) - Automate rule discovery
