🔍 Code Extractor

function validate_document_number

Maturity: 54

Validates a custom document number by checking its format, length constraints, and uniqueness in the database, returning a dictionary with validation results.

File:
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
Lines:
271 - 321
Complexity:
moderate

Purpose

This function ensures that document numbers conform to specific formatting rules (uppercase letters, numbers, hyphens, underscores only), meet length requirements (3-50 characters), and are unique within the system. It's used in document management workflows to prevent duplicate document numbers and enforce naming conventions before document creation or updates.

Source Code

def validate_document_number(doc_number: str) -> Dict[str, Any]:
    """
    Validate if a custom document number is available and properly formatted.
    
    Args:
        doc_number: The document number to validate
        
    Returns:
        Dictionary with validation results
    """
    try:
        # Check format
        if not re.match(r'^[A-Z0-9\-_]+$', doc_number):
            return {
                "valid": False,
                "message": "Document number can only contain uppercase letters, numbers, hyphens, and underscores"
            }
            
        # Check length
        if len(doc_number) < 3 or len(doc_number) > 50:
            return {
                "valid": False,
                "message": "Document number must be between 3 and 50 characters"
            }
        
        # Check uniqueness
        existing_doc = db.run_query(
            """
            MATCH (d:ControlledDocument {docNumber: $doc_number})
            RETURN d.UID as uid, d.title as title
            """,
            {"doc_number": doc_number}
        )
        
        if existing_doc:
            return {
                "valid": False,
                "message": f"Document number '{doc_number}' is already in use by: {existing_doc[0].get('title', 'Unknown Document')}"
            }
        
        return {
            "valid": True,
            "message": f"Document number '{doc_number}' is available"
        }
        
    except Exception as e:
        logger.error(f"Error validating document number: {e}")
        return {
            "valid": False,
            "message": f"Error validating document number: {str(e)}"
        }

Parameters

Name Type Default Kind
doc_number str - positional_or_keyword

Parameter Details

doc_number: The document number string to validate. Expected to contain only uppercase letters (A-Z), numbers (0-9), hyphens (-), and underscores (_). Must be between 3 and 50 characters in length. This is typically a user-provided identifier for a controlled document.

Return Value

Type: Dict[str, Any]

Returns a dictionary with two keys: 'valid' (boolean indicating whether the document number passes all validation checks) and 'message' (string providing details about the validation result, including error descriptions or success confirmation). If validation fails, the message explains which constraint was violated. If an exception occurs, valid is False and message contains the error details.

Dependencies

  • re
  • logging
  • typing
  • CDocs.db
  • CDocs.controllers

Required Imports

import re
from typing import Dict, Any
from CDocs import db
import logging

Usage Example

from CDocs.controllers.document_controller import validate_document_number

# Validate a document number
result = validate_document_number('DOC-2024-001')

if result['valid']:
    print(f"Success: {result['message']}")
    # Proceed with document creation
else:
    print(f"Validation failed: {result['message']}")
    # Show error to user

# Example outputs:
# Valid: {'valid': True, 'message': "Document number 'DOC-2024-001' is available"}
# Invalid format: {'valid': False, 'message': 'Document number can only contain uppercase letters, numbers, hyphens, and underscores'}
# Too short: {'valid': False, 'message': 'Document number must be between 3 and 50 characters'}
# Duplicate: {'valid': False, 'message': "Document number 'DOC-2024-001' is already in use by: Quality Manual"}

Best Practices

  • Always check the 'valid' key in the returned dictionary before proceeding with document operations
  • Display the 'message' value to users for clear feedback on validation failures
  • Ensure document numbers are converted to uppercase before validation if case-insensitive input is allowed
  • This function performs a database query, so consider caching results if validating the same number multiple times
  • The function is decorated with log_controller_action, so all calls are automatically logged for audit purposes
  • Handle the exception case gracefully - even though exceptions are caught internally, the database connection must be available
  • Use this validation before attempting to create or update documents to prevent constraint violations at the database level

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function check_document_exists_by_doc_number 74.0% similar

    Queries a Neo4j database to check if a ControlledDocument exists with a specific document number and returns the document object if found.

    From: /tf/active/vicechatdev/CDocs/FC_sync.py
  • function generate_document_number 65.5% similar

    Generates unique, sequential document numbers for a given document type and department using persistent counters stored in Neo4j database.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function generate_document_number_v1 62.5% similar

    Generates a unique document number by combining document type code, department code, and using a settings-based generation function, with UUID fallback on error.

    From: /tf/active/vicechatdev/document_controller_backup.py
  • function validate_document 59.2% similar

    Validates document files by checking file size, extension, and optionally performing type-specific structural validation for supported document formats.

    From: /tf/active/vicechatdev/CDocs/utils/document_processor.py
  • function validate_and_fix_document_permissions 58.0% similar

    Validates and optionally fixes document sharing permissions for controlled documents in a Neo4j database, processing documents in configurable batches with detailed progress tracking and error handling.

    From: /tf/active/vicechatdev/CDocs/utils/sharing_validator.py
← Back to Browse