function validate_document_number
Validates a custom document number by checking its format, length constraints, and uniqueness in the database, returning a dictionary with validation results.
/tf/active/vicechatdev/CDocs/controllers/document_controller.py
271 - 321
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
reloggingtypingCDocs.dbCDocs.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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function check_document_exists_by_doc_number 74.0% similar
-
function generate_document_number 65.5% similar
-
function generate_document_number_v1 62.5% similar
-
function validate_document 59.2% similar
-
function validate_and_fix_document_permissions 58.0% similar