Documentation
¶
Overview ¶
Package validator provides comprehensive data format validation for Go applications.
The validator package supports validation of multiple data formats including JSON, YAML, XML, TOML, CSV, GraphQL, INI, HCL, Protobuf text format, Markdown, JSON Lines, Jupyter Notebooks, Python requirements.txt, and Dockerfiles. It features automatic format detection and a unified API for all supported formats.
Features ¶
- Support for 15+ data formats
- Automatic format detection from content or filename
- Zero dependencies for core validation logic
- Thread-safe validator implementations
- Simple, consistent API across all formats
- Privacy-focused: no logging, network calls, or data retention
- Comprehensive error messages for validation failures
Basic Usage ¶
Create a validator for a specific format:
import "github.com/akhilesharora/serdeval"
// Create a JSON validator
v, err := serdeval.NewValidator(serdeval.FormatJSON)
if err != nil {
log.Fatal(err)
}
// Validate a string
result := v.ValidateString(`{"name": "test", "value": 123}`)
if result.Valid {
fmt.Println("Valid JSON!")
} else {
fmt.Printf("Invalid JSON: %s\n", result.Error)
}
Automatic Format Detection ¶
Use ValidateAuto for automatic format detection:
data := []byte(`{"key": "value"}`)
result := serdeval.ValidateAuto(data)
fmt.Printf("Detected format: %s\n", result.Format)
fmt.Printf("Valid: %v\n", result.Valid)
Detect format from filename:
format := serdeval.DetectFormatFromFilename("config.yaml")
// format == serdeval.FormatYAML
Supported Formats ¶
The package supports the following formats:
- JSON (FormatJSON): RFC 7159 compliant JSON validation
- YAML (FormatYAML): YAML 1.2 specification
- XML (FormatXML): Well-formed XML validation
- TOML (FormatTOML): TOML v1.0.0 format
- CSV (FormatCSV): Comma-separated values with consistent columns
- GraphQL (FormatGraphQL): GraphQL queries, mutations, and schemas
- INI (FormatINI): INI configuration files with sections
- HCL (FormatHCL): HashiCorp Configuration Language (HCL2)
- Protobuf (FormatProtobuf): Protocol Buffers text format
- Markdown (FormatMarkdown): CommonMark specification
- JSON Lines (FormatJSONL): Newline-delimited JSON
- Jupyter (FormatJupyter): Jupyter Notebook .ipynb files
- Requirements (FormatRequirements): Python requirements.txt
- Dockerfile (FormatDockerfile): Docker container definitions
Advanced Usage ¶
Validate multiple files with different formats:
files := []string{"config.json", "data.yaml", "schema.graphql"}
for _, file := range files {
data, err := os.ReadFile(file)
if err != nil {
log.Printf("Error reading %s: %v", file, err)
continue
}
// Detect format from filename
format := serdeval.DetectFormatFromFilename(file)
if format == serdeval.FormatUnknown {
// Fall back to content detection
format = serdeval.DetectFormat(data)
}
// Create appropriate validator
v, err := serdeval.NewValidator(format)
if err != nil {
log.Printf("Unsupported format for %s", file)
continue
}
// Validate the file
result := v.Validate(data)
result.FileName = file
if result.Valid {
fmt.Printf("✓ %s: Valid %s\n", file, result.Format)
} else {
fmt.Printf("✗ %s: %s\n", file, result.Error)
}
}
Format Detection Heuristics ¶
The package uses intelligent heuristics for format detection:
- File extension matching for reliable format identification
- Content-based detection using format-specific patterns
- Precedence given to more specific formats (e.g., Jupyter over JSON)
- Support for files without extensions (e.g., Dockerfile)
Privacy and Security ¶
This package is designed with privacy and security in mind:
- All validation is performed in-memory
- No network connections are made
- No temporary files are created
- No data is logged or retained
- Input data is never modified
Thread Safety ¶
All validator implementations are thread-safe and can be reused across multiple goroutines:
validator, _ := serdeval.NewValidator(serdeval.FormatJSON)
// Safe to use concurrently
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(data string) {
defer wg.Done()
result := serdeval.ValidateString(data)
// Process result
}(jsonData[i])
}
wg.Wait()
Error Handling ¶
Validation errors include detailed information about what went wrong:
result := serdeval.ValidateString(invalidJSON)
if !result.Valid {
// result.Error contains specific error message
// e.g., "unexpected end of JSON input"
fmt.Printf("Validation failed: %s\n", result.Error)
}
Package serdeval provides data format validation for JSON, YAML, XML, TOML, CSV, GraphQL, INI, HCL, Protobuf text format, Markdown, JSON Lines, Jupyter Notebooks, Requirements.txt, and Dockerfile
Index ¶
- type CSVValidator
- type DockerfileValidator
- type Format
- type GraphQLValidator
- type HCLValidator
- type INIValidator
- type JSONLValidator
- type JSONValidator
- type JupyterValidator
- type MarkdownValidator
- type ProtobufValidator
- type RequirementsValidator
- type Result
- type TOMLValidator
- type Validator
- type XMLValidator
- type YAMLValidator
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CSVValidator ¶
type CSVValidator struct {
// contains filtered or unexported fields
}
CSVValidator validates CSV (Comma-Separated Values) data. It checks that the data can be parsed as valid CSV with consistent column counts.
Example:
validator := &CSVValidator{baseValidator{format: FormatCSV}}
result := validator.ValidateString("name,age\nJohn,30\nJane,25")
func (CSVValidator) Format ¶
func (v CSVValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*CSVValidator) Validate ¶
func (v *CSVValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid CSV data. It reads all records to ensure consistent column counts and proper formatting.
Example:
validator := &CSVValidator{baseValidator{format: FormatCSV}}
result := validator.Validate([]byte("name,age\nJohn,30"))
func (*CSVValidator) ValidateString ¶
func (v *CSVValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a CSV string. It converts the string to bytes and calls Validate.
Example:
validator := &CSVValidator{baseValidator{format: FormatCSV}}
result := validator.ValidateString("header1,header2\nvalue1,value2")
type DockerfileValidator ¶
type DockerfileValidator struct {
// contains filtered or unexported fields
}
DockerfileValidator validates Dockerfile syntax. It checks for valid Docker instructions and ensures at least one FROM instruction exists.
Example:
validator := &DockerfileValidator{baseValidator{format: FormatDockerfile}}
result := validator.ValidateString("FROM golang:1.19\nWORKDIR /app\nCOPY . .")
func (DockerfileValidator) Format ¶
func (v DockerfileValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*DockerfileValidator) Validate ¶
func (v *DockerfileValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid Dockerfile syntax. It verifies that valid Docker instructions are used and at least one FROM instruction exists. Line continuations with backslash are supported.
Example:
validator := &DockerfileValidator{baseValidator{format: FormatDockerfile}}
result := validator.Validate([]byte("FROM alpine:latest\nRUN apk add --no-cache curl"))
func (*DockerfileValidator) ValidateString ¶
func (v *DockerfileValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a Dockerfile string. It converts the string to bytes and calls Validate.
Example:
validator := &DockerfileValidator{baseValidator{format: FormatDockerfile}}
result := validator.ValidateString("FROM node:16\nWORKDIR /app\nCOPY . .")
type Format ¶
type Format string
Format represents a supported data format type. It is used to specify which validator to use and identify detected formats.
const ( // FormatJSON represents JSON format FormatJSON Format = "json" // FormatYAML represents YAML format FormatYAML Format = "yaml" // FormatXML represents XML format FormatXML Format = "xml" // FormatTOML represents TOML format FormatTOML Format = "toml" // FormatCSV represents CSV format FormatCSV Format = "csv" // FormatGraphQL represents GraphQL query/schema format FormatGraphQL Format = "graphql" // FormatINI represents INI configuration format FormatINI Format = "ini" // FormatHCL represents HCL (HashiCorp Configuration Language) format FormatHCL Format = "hcl" // FormatProtobuf represents Protobuf text format FormatProtobuf Format = "protobuf" // FormatMarkdown represents Markdown format FormatMarkdown Format = "markdown" // FormatJSONL represents JSON Lines format (newline-delimited JSON) FormatJSONL Format = "jsonl" // FormatJupyter represents Jupyter Notebook format FormatJupyter Format = "jupyter" // FormatRequirements represents Requirements.txt format FormatRequirements Format = "requirements" // FormatDockerfile represents Dockerfile format FormatDockerfile Format = "dockerfile" // FormatAuto represents automatic format detection FormatAuto Format = "auto" // FormatUnknown represents unknown format FormatUnknown Format = "unknown" )
func DetectFormat ¶
DetectFormat attempts to detect the data format by analyzing the content. Uses simple heuristics to identify various data formats.
Detection rules:
- JSON: Starts with '{' or '['
- XML: Starts with '<?xml' or '<'
- YAML: Contains '---' or has key:value pattern
- TOML: Contains '[section]' pattern with key=value pairs
- CSV: Has comma-separated values with consistent columns
- GraphQL: Contains query/mutation/type/schema keywords
- INI: Has [section] headers or key=value pairs
- Dockerfile: Starts with FROM instruction
- Markdown: Contains markdown syntax like #, *, -, ```
- Requirements.txt: Contains package names with version specifiers
Returns FormatUnknown if the format cannot be determined.
func DetectFormatFromFilename ¶
DetectFormatFromFilename attempts to detect format from filename extension.
Supported extensions:
- .json → FormatJSON
- .yaml, .yml → FormatYAML
- .xml → FormatXML
- .toml → FormatTOML
Example:
format := DetectFormatFromFilename("config.json")
// format == FormatJSON
Returns FormatUnknown if the extension is not recognized.
type GraphQLValidator ¶
type GraphQLValidator struct {
// contains filtered or unexported fields
}
GraphQLValidator validates GraphQL queries, mutations, subscriptions, and schema definitions. It uses the GraphQL parser to ensure syntactic validity.
Example:
validator := &GraphQLValidator{baseValidator{format: FormatGraphQL}}
result := validator.ValidateString(`query { user(id: "123") { name email } }`)
func (GraphQLValidator) Format ¶
func (v GraphQLValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*GraphQLValidator) Validate ¶
func (v *GraphQLValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid GraphQL syntax. It can validate queries, mutations, subscriptions, and schema definitions. Empty content is considered invalid.
Example:
validator := &GraphQLValidator{baseValidator{format: FormatGraphQL}}
result := validator.Validate([]byte(`query { user { name } }`))
func (*GraphQLValidator) ValidateString ¶
func (v *GraphQLValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a GraphQL string. It converts the string to bytes and calls Validate.
Example:
validator := &GraphQLValidator{baseValidator{format: FormatGraphQL}}
result := validator.ValidateString(`mutation { createUser(name: "John") { id } }`)
type HCLValidator ¶
type HCLValidator struct {
// contains filtered or unexported fields
}
HCLValidator validates HCL (HashiCorp Configuration Language) data. It supports HCL2 syntax used in Terraform, Packer, and other HashiCorp tools.
Example:
validator := &HCLValidator{baseValidator{format: FormatHCL}}
result := validator.ValidateString(`resource "aws_instance" "example" { ami = "ami-123" }`)
func (HCLValidator) Format ¶
func (v HCLValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*HCLValidator) Validate ¶
func (v *HCLValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid HCL2 syntax. It uses the HashiCorp HCL parser to validate the configuration.
Example:
validator := &HCLValidator{baseValidator{format: FormatHCL}}
result := validator.Validate([]byte(`variable "region" { default = "us-west-2" }`))
func (*HCLValidator) ValidateString ¶
func (v *HCLValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates an HCL string. It converts the string to bytes and calls Validate.
Example:
validator := &HCLValidator{baseValidator{format: FormatHCL}}
result := validator.ValidateString(`resource "aws_instance" "web" { ami = "ami-123" }`)
type INIValidator ¶
type INIValidator struct {
// contains filtered or unexported fields
}
INIValidator validates INI configuration file format. It supports sections, key-value pairs, and comments.
Example:
validator := &INIValidator{baseValidator{format: FormatINI}}
result := validator.ValidateString(`[database]\nhost = localhost\nport = 5432`)
func (INIValidator) Format ¶
func (v INIValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*INIValidator) Validate ¶
func (v *INIValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid INI format data. It supports sections, key-value pairs, and comments.
Example:
validator := &INIValidator{baseValidator{format: FormatINI}}
result := validator.Validate([]byte(`[section]\nkey = value`))
func (*INIValidator) ValidateString ¶
func (v *INIValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates an INI string. It converts the string to bytes and calls Validate.
Example:
validator := &INIValidator{baseValidator{format: FormatINI}}
result := validator.ValidateString("[database]\nhost = localhost")
type JSONLValidator ¶
type JSONLValidator struct {
// contains filtered or unexported fields
}
JSONLValidator validates JSON Lines (newline-delimited JSON) data. Each line must be a valid JSON object or array.
Example:
validator := &JSONLValidator{baseValidator{format: FormatJSONL}}
result := validator.ValidateString(`{"name": "John"}\n{"name": "Jane"}`)
func (JSONLValidator) Format ¶
func (v JSONLValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*JSONLValidator) Validate ¶
func (v *JSONLValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid JSON Lines format. Each non-empty line must be a valid JSON object or array. Empty lines are allowed and ignored.
Example:
validator := &JSONLValidator{baseValidator{format: FormatJSONL}}
result := validator.Validate([]byte(`{"id":1}\n{"id":2}`))
func (*JSONLValidator) ValidateString ¶
func (v *JSONLValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a JSON Lines string. It converts the string to bytes and calls Validate.
Example:
validator := &JSONLValidator{baseValidator{format: FormatJSONL}}
result := validator.ValidateString(`{"event":"start"}\n{"event":"end"}`)
type JSONValidator ¶
type JSONValidator struct {
// contains filtered or unexported fields
}
JSONValidator validates JSON data according to RFC 7159. It supports validation of both JSON objects and arrays.
Example:
validator := &JSONValidator{baseValidator{format: FormatJSON}}
result := validator.ValidateString(`{"name": "test", "value": 123}`)
func (JSONValidator) Format ¶
func (v JSONValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*JSONValidator) Validate ¶
func (v *JSONValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid JSON data. It attempts to unmarshal the data and returns a Result indicating success or failure.
The validation checks for proper JSON syntax including:
- Matching braces and brackets
- Proper string escaping
- Valid number formats
- Correct use of null, true, and false
Example:
validator := &JSONValidator{baseValidator{format: FormatJSON}}
result := validator.Validate([]byte(`{"valid": true}`))
if result.Valid {
fmt.Println("Valid JSON!")
}
func (*JSONValidator) ValidateString ¶
func (v *JSONValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a JSON string. It converts the string to bytes and calls Validate.
Example:
validator := &JSONValidator{baseValidator{format: FormatJSON}}
result := validator.ValidateString(`{"name": "test"}`)
type JupyterValidator ¶
type JupyterValidator struct {
// contains filtered or unexported fields
}
JupyterValidator validates Jupyter Notebook (.ipynb) files. It checks for the required notebook structure including cells, metadata, and nbformat.
Example:
validator := &JupyterValidator{baseValidator{format: FormatJupyter}}
result := validator.Validate(jupyterNotebookBytes)
func (JupyterValidator) Format ¶
func (v JupyterValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*JupyterValidator) Validate ¶
func (v *JupyterValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains a valid Jupyter Notebook. It verifies that the data is valid JSON and contains required notebook fields: cells, metadata, and nbformat.
Example:
validator := &JupyterValidator{baseValidator{format: FormatJupyter}}
notebookData, _ := os.ReadFile("notebook.ipynb")
result := validator.Validate(notebookData)
func (*JupyterValidator) ValidateString ¶
func (v *JupyterValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a Jupyter Notebook string. It converts the string to bytes and calls Validate.
Example:
validator := &JupyterValidator{baseValidator{format: FormatJupyter}}
result := validator.ValidateString(notebookJSONString)
type MarkdownValidator ¶
type MarkdownValidator struct {
// contains filtered or unexported fields
}
MarkdownValidator validates Markdown formatted text. It uses the CommonMark specification to parse and validate the content.
Example:
validator := &MarkdownValidator{baseValidator{format: FormatMarkdown}}
result := validator.ValidateString("# Title\n\nThis is **bold** text.")
func (MarkdownValidator) Format ¶
func (v MarkdownValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*MarkdownValidator) Validate ¶
func (v *MarkdownValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid Markdown. It uses the CommonMark specification to parse the content.
Example:
validator := &MarkdownValidator{baseValidator{format: FormatMarkdown}}
result := validator.Validate([]byte("# Title\n\nParagraph with **bold** text."))
func (*MarkdownValidator) ValidateString ¶
func (v *MarkdownValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a Markdown string. It converts the string to bytes and calls Validate.
Example:
validator := &MarkdownValidator{baseValidator{format: FormatMarkdown}}
result := validator.ValidateString("## Heading\n\n- List item 1\n- List item 2")
type ProtobufValidator ¶
type ProtobufValidator struct {
// contains filtered or unexported fields
}
ProtobufValidator validates Protocol Buffers text format data. It checks that the data can be parsed as valid protobuf text format.
Example:
validator := &ProtobufValidator{baseValidator{format: FormatProtobuf}}
result := validator.ValidateString(`type_url: "type.googleapis.com/Example" value: "\x08\x01"`)
func (ProtobufValidator) Format ¶
func (v ProtobufValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*ProtobufValidator) Validate ¶
func (v *ProtobufValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid Protocol Buffers text format. It attempts to unmarshal the data as protobuf text format.
Example:
validator := &ProtobufValidator{baseValidator{format: FormatProtobuf}}
result := validator.Validate([]byte(`type_url: "example.com/Type"`))
func (*ProtobufValidator) ValidateString ¶
func (v *ProtobufValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a Protobuf text format string. It converts the string to bytes and calls Validate.
Example:
validator := &ProtobufValidator{baseValidator{format: FormatProtobuf}}
result := validator.ValidateString(`type_url: "type.googleapis.com/Example"`)
type RequirementsValidator ¶
type RequirementsValidator struct {
// contains filtered or unexported fields
}
RequirementsValidator validates Python requirements.txt file format. It supports package names with version specifiers (==, >=, <=, ~=) and comments.
Example:
validator := &RequirementsValidator{baseValidator{format: FormatRequirements}}
result := validator.ValidateString("flask==2.0.1\nrequests>=2.25.0")
func (RequirementsValidator) Format ¶
func (v RequirementsValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*RequirementsValidator) Validate ¶
func (v *RequirementsValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid requirements.txt format. It supports package names with version specifiers and comments. Empty lines and lines starting with # are allowed.
Example:
validator := &RequirementsValidator{baseValidator{format: FormatRequirements}}
result := validator.Validate([]byte("django==3.2\nrequests>=2.25.0"))
func (*RequirementsValidator) ValidateString ¶
func (v *RequirementsValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a requirements.txt string. It converts the string to bytes and calls Validate.
Example:
validator := &RequirementsValidator{baseValidator{format: FormatRequirements}}
result := validator.ValidateString("numpy>=1.19.0\npandas==1.3.0")
type Result ¶
type Result struct {
// Valid indicates whether the data is valid for the detected/specified format
Valid bool `json:"valid"`
// Format indicates the data format that was validated
Format Format `json:"format"`
// Error contains the validation error message if Valid is false
Error string `json:"error,omitempty"`
// FileName is an optional field to track which file was validated
FileName string `json:"filename,omitempty"`
}
Result contains the validation result for a data format validation operation. It provides information about whether the validation succeeded, the format that was validated, and any error messages if validation failed.
Example:
result := validator.ValidateString(`{"key": "value"}`)
if result.Valid {
fmt.Printf("Valid %s data\n", result.Format)
} else {
fmt.Printf("Invalid data: %s\n", result.Error)
}
func ValidateAuto ¶
ValidateAuto validates data with automatic format detection. It first attempts to detect the format, then validates using the appropriate validator.
Example:
data := []byte(`{"name": "test"}`)
result := ValidateAuto(data)
fmt.Printf("Format: %s, Valid: %v\n", result.Format, result.Valid)
// Output: Format: json, Valid: true
Returns a Result with Format=FormatUnknown if the format cannot be detected.
type TOMLValidator ¶
type TOMLValidator struct {
// contains filtered or unexported fields
}
TOMLValidator validates TOML (Tom's Obvious, Minimal Language) data. It supports all TOML v1.0.0 features including tables, arrays, and inline tables.
Example:
validator := &TOMLValidator{baseValidator{format: FormatTOML}}
result := validator.ValidateString(`[server]\nhost = "localhost"\nport = 8080`)
func (TOMLValidator) Format ¶
func (v TOMLValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*TOMLValidator) Validate ¶
func (v *TOMLValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid TOML data. It supports all TOML v1.0.0 features.
Example:
validator := &TOMLValidator{baseValidator{format: FormatTOML}}
result := validator.Validate([]byte(`[server]\nport = 8080`))
func (*TOMLValidator) ValidateString ¶
func (v *TOMLValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a TOML string. It converts the string to bytes and calls Validate.
Example:
validator := &TOMLValidator{baseValidator{format: FormatTOML}}
result := validator.ValidateString(`title = "TOML Example"`)
type Validator ¶
type Validator interface {
// Validate checks if the provided byte slice is valid for this validator's format.
// Returns a Result containing validation status and any error messages.
Validate(data []byte) Result
// ValidateString is a convenience method that validates a string.
// Internally converts the string to []byte and calls Validate.
ValidateString(data string) Result
// Format returns the data format this validator is configured for.
Format() Format
}
Validator is the main interface for validating data formats. Each validator implementation is specific to a single format.
Implementations are thread-safe and can be reused for multiple validations.
Example:
validator, err := NewValidator(FormatJSON)
if err != nil {
log.Fatal(err)
}
// Validate bytes
result := validator.Validate(jsonBytes)
// Or validate string
result := validator.ValidateString(jsonString)
func NewValidator ¶
NewValidator creates a new validator for the specified format.
Example:
validator, err := NewValidator(FormatJSON)
if err != nil {
log.Fatal(err)
}
result := validator.ValidateString(`{"key": "value"}`)
if result.Valid {
fmt.Println("Valid JSON!")
}
Supported formats: FormatJSON, FormatYAML, FormatXML, FormatTOML, FormatCSV, FormatGraphQL, FormatINI, FormatHCL, FormatProtobuf, FormatMarkdown, FormatJSONL, FormatJupyter, FormatRequirements, FormatDockerfile Returns an error if an unsupported format is specified.
type XMLValidator ¶
type XMLValidator struct {
// contains filtered or unexported fields
}
XMLValidator validates XML data for well-formedness. It checks that the XML is properly structured with matching tags and valid syntax.
Note: This validator checks for well-formedness only, not validity against a schema.
Example:
validator := &XMLValidator{baseValidator{format: FormatXML}}
result := validator.ValidateString(`<root><item>test</item></root>`)
func (XMLValidator) Format ¶
func (v XMLValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*XMLValidator) Validate ¶
func (v *XMLValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains well-formed XML data. Note that this only checks for well-formedness, not validity against a schema.
Example:
validator := &XMLValidator{baseValidator{format: FormatXML}}
result := validator.Validate([]byte(`<?xml version="1.0"?><root></root>`))
func (*XMLValidator) ValidateString ¶
func (v *XMLValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates an XML string. It converts the string to bytes and calls Validate.
Example:
validator := &XMLValidator{baseValidator{format: FormatXML}}
result := validator.ValidateString(`<root><item>test</item></root>`)
type YAMLValidator ¶
type YAMLValidator struct {
// contains filtered or unexported fields
}
YAMLValidator validates YAML data according to YAML 1.2 specification. It supports all standard YAML features including anchors, aliases, and multi-document streams.
Example:
validator := &YAMLValidator{baseValidator{format: FormatYAML}}
result := validator.ValidateString("name: test\nvalue: 123")
func (YAMLValidator) Format ¶
func (v YAMLValidator) Format() Format
Format returns the data format type associated with this validator. This method is available on all validator implementations.
Example:
validator, _ := NewValidator(FormatJSON) fmt.Println(validator.Format()) // Output: json
func (*YAMLValidator) Validate ¶
func (v *YAMLValidator) Validate(data []byte) Result
Validate checks if the provided byte slice contains valid YAML data. It supports all YAML 1.2 features including multi-document streams.
Example:
validator := &YAMLValidator{baseValidator{format: FormatYAML}}
result := validator.Validate([]byte("key: value\nlist:\n - item1\n - item2"))
func (*YAMLValidator) ValidateString ¶
func (v *YAMLValidator) ValidateString(data string) Result
ValidateString is a convenience method that validates a YAML string. It converts the string to bytes and calls Validate.
Example:
validator := &YAMLValidator{baseValidator{format: FormatYAML}}
result := validator.ValidateString("name: test\nvalue: 123")