mowgli

package module
v0.0.0-...-44ffe68 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2025 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Mowgli - JSON Validation Library

Mowgli is a validation library for Go and JavaScript that validates JSON data using a JSON-based specification format. The spec format is designed to work in both languages, making it useful for projects that need consistent validation across backend and frontend.

Features

Mowgli supports standard JSON types (string, number, integer, boolean, object, array, null) with constraints like min/max values, string lengths, regex patterns, and enums. It also includes conditional validation where field requirements can depend on other field values.

The library is still being developed and missing some features, but provides a solid foundation for JSON validation needs. Future versions will expand on these capabilities.

Quick Start

Go - Using JSON Specs
import "github.com/matjam/mowgli"

specJSON := `{
  "type": "object",
  "properties": {
    "name": {"type": "string", "minLength": 1, "maxLength": 100},
    "age": {"type": "integer", "min": 0, "max": 150}
  },
  "required": ["name"]
}`

spec, _ := mowgli.ParseSpecString(specJSON)
data := map[string]any{"name": "John", "age": 30}
result := mowgli.Validate(data, spec)

if !result.Valid {
    for _, err := range result.Errors {
        fmt.Printf("%s: %s\n", err.Path, err.Message)
    }
}
Go - Using Struct Tags
type User struct {
    Name string `json:"name" mowgli:"required,minLength=1,maxLength=100"`
    Age  int    `json:"age" mowgli:"min=0,max=150"`
}

data := map[string]any{"name": "John", "age": 30}
result, user, err := mowgli.ValidateStruct[User](data)
// user is of type User, fully typed and validated
JavaScript/TypeScript
import { validate, parseSpec } from 'mowgli';

const spec = parseSpec(`{
  "type": "object",
  "properties": {
    "name": {"type": "string", "minLength": 1}
  },
  "required": ["name"]
}`);

const result = validate({name: "John"}, spec);
if (!result.valid) {
    result.errors.forEach(err => console.error(`${err.path}: ${err.message}`));
}
Client-Side Form Validation

Mowgli provides framework-agnostic helpers that work with any JavaScript framework (React, Vue, Svelte, Angular, vanilla JS, etc.):

import { fetchSpec, createFormValidator, groupErrorsByField } from 'mowgli';

// Fetch validation spec from API endpoint
const spec = await fetchSpec('/api/users', {
  headerName: 'X-Mowgli',
  headerValue: 'Validation Request'
});

// Create a reusable validator
const validator = createFormValidator(spec);

// Validate entire form on submit
const formValues = { username: 'john', email: 'john@example.com', password: 'pass123' };
const result = validator.validateForm(formValues);
if (!result.valid) {
  const errorsByField = groupErrorsByField(result);
  // Display errors to user
  // { username: "string length 4 is less than minimum 5", ... }
}

// Validate single field on change (for real-time feedback)
const fieldResult = validator.validateField('username', 'ab', formValues);
if (!fieldResult.valid) {
  // Show error for this field: fieldResult.error
  // "string length 2 is less than minimum 3"
}

Available helpers:

  • fetchSpec - Fetches and parses a validation spec from an API endpoint
  • validateField - Validates a single field in isolation (with form context for conditional validation)
  • groupErrorsByField - Groups validation errors by field name (first error per field)
  • groupAllErrorsByField - Groups all validation errors by field name (all errors per field)
  • createFormValidator - Creates a reusable validator with helper methods for a spec

Example: Using with a framework

Here's how you might use these helpers in a React component (or similar pattern for Vue/Svelte/etc.):

import { useState, useEffect } from 'react';
import { fetchSpec, createFormValidator, groupErrorsByField } from 'mowgli';

function UserRegistrationForm() {
  const [values, setValues] = useState({ username: '', email: '', password: '' });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [validator, setValidator] = useState<any>(null);

  useEffect(() => {
    fetchSpec('/api/users').then(spec => {
      setValidator(createFormValidator(spec));
    });
  }, []);

  const handleChange = (field: string, value: string) => {
    const newValues = { ...values, [field]: value };
    setValues(newValues);
    
    // Real-time field validation
    if (validator) {
      const result = validator.validateField(field, value, newValues);
      setErrors(prev => ({
        ...prev,
        [field]: result.error || ''
      }));
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!validator) return;
    
    const result = validator.validateForm(values);
    if (!result.valid) {
      setErrors(groupErrorsByField(result));
      return;
    }
    
    // Submit form...
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={values.username}
        onChange={(e) => handleChange('username', e.target.value)}
      />
      {errors.username && <span>{errors.username}</span>}
      {/* ... more fields ... */}
    </form>
  );
}

These helpers work with any framework—you just integrate them with your framework's state management and event handling patterns.

Examples

The examples/ directory contains working examples demonstrating various use cases:

Each example includes comprehensive tests showing both valid and invalid inputs.

API Service Usage

Mowgli is designed to work seamlessly in API services where you want to validate request payloads and provide schema discovery. The recommended pattern is:

  1. POST/PUT requests - Validate the request body against your spec
  2. GET requests with schema discovery - Return the validation spec when requested with a special header or query parameter
Example Pattern
// Example endpoint handler
func handleUserEndpoint(w http.ResponseWriter, r *http.Request) {
    // Schema discovery: GET with X-Mowgli header returns the spec
    if r.Method == "GET" && r.Header.Get("X-Mowgli") == "Validation Request" {
        spec, _ := LoadSpec("user_registration.json")
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(spec)
        return
    }
    
    // Validation: POST/PUT validates the request body
    if r.Method == "POST" || r.Method == "PUT" {
        var data map[string]any
        json.NewDecoder(r.Body).Decode(&data)
        
        spec, _ := LoadSpec("user_registration.json")
        result := mowgli.Validate(data, spec)
        
        if !result.Valid {
            w.WriteHeader(http.StatusBadRequest)
            json.NewEncoder(w).Encode(result.Errors)
            return
        }
        
        // Process valid data...
    }
}

This pattern allows API clients to:

  • Discover validation requirements by making a GET request with the X-Mowgli: Validation Request header (or your preferred header/query parameter)
  • Validate payloads on the server side before processing
  • Use the same spec format for both server-side validation and client-side validation (with the JavaScript library)

The header name and format are flexible—you can use any header name or query parameter that suits your API design.

Specification Format

Specs are JSON objects that define type and constraints. See example_spec.json for a complete example.

Supported constraints:

  • Strings: minLength, maxLength, pattern, enum, allowEmpty
  • Numbers/Integers: min, max, enum
  • Arrays: minLength, maxLength, items (for item validation)
  • Objects: properties, required, conditions (for conditional validation)

Conditional validation uses simple expressions in the if field (e.g., "enabled == true", "count > 0") and applies spec overrides in then/else blocks.

Installation

Go:

go get github.com/matjam/mowgli

JavaScript/TypeScript:

yarn add mowgli
# or
npm install mowgli

License

MIT

Acknowledgments

An LLM was used extensively to help with the implementation of this library. The code was carefully inspected, tested, and adjusted by humans to ensure a clean and accurate implementation.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Condition

type Condition struct {
	If   string           `json:"if"`             // Expression to evaluate, e.g., "enabled == true", "count > 0"
	Then map[string]*Spec `json:"then"`           // Spec overrides to apply when condition is true
	Else map[string]*Spec `json:"else,omitempty"` // Spec overrides to apply when condition is false
}

Condition defines a conditional validation rule

type Spec

type Spec struct {
	Type       string           `json:"type"`                 // string, number, integer, boolean, object, array, null
	Properties map[string]*Spec `json:"properties,omitempty"` // For object type
	Items      *Spec            `json:"items,omitempty"`      // For array type
	Required   []string         `json:"required,omitempty"`   // For object type - list of required property names
	Conditions []Condition      `json:"conditions,omitempty"` // Conditional validation rules for object type

	// Constraints
	Min        *float64 `json:"min,omitempty"`        // For number/integer - minimum value
	Max        *float64 `json:"max,omitempty"`        // For number/integer - maximum value
	MinLength  *int     `json:"minLength,omitempty"`  // For string/array - minimum length
	MaxLength  *int     `json:"maxLength,omitempty"`  // For string/array - maximum length
	Pattern    *string  `json:"pattern,omitempty"`    // For string - regex pattern (future: could support regex validation)
	Enum       []any    `json:"enum,omitempty"`       // Array of allowed values
	AllowEmpty *bool    `json:"allowEmpty,omitempty"` // For strings - allows empty string if true
}

Spec defines the validation specification structure

func GetSpecFromStruct

func GetSpecFromStruct[T any](structValue T) (*Spec, error)

GetSpecFromStruct generates a Spec from a struct type This is a convenience function that can be used to get the spec for a struct type

func LoadSpec

func LoadSpec(filename string) (*Spec, error)

LoadSpec loads a spec JSON file from the testdata directory

func MergeSpecs

func MergeSpecs(base, override *Spec) *Spec

MergeSpecs merges two specs, with override taking precedence

func ParseSpec

func ParseSpec(data []byte) (*Spec, error)

ParseSpec parses a JSON byte slice into a Spec

func ParseSpecString

func ParseSpecString(s string) (*Spec, error)

ParseSpecString parses a JSON string into a Spec

func SpecFromStruct

func SpecFromStruct(v any) (*Spec, error)

SpecFromStruct generates a Spec from a struct type using reflection and struct tags

type StructTagOptions

type StructTagOptions struct {
	Required   bool
	Min        *float64
	Max        *float64
	MinLength  *int
	MaxLength  *int
	Pattern    *string
	Enum       []any
	AllowEmpty *bool
}

StructTagOptions holds parsed validation options from struct tags

func ParseStructTag

func ParseStructTag(tag string) (*StructTagOptions, error)

ParseStructTag parses a mowgli struct tag and returns validation options Example: `mowgli:"required,min=0,max=100,minLength=1"`

type TestCase

type TestCase struct {
	Name          string         `json:"name"`
	Data          map[string]any `json:"data"`
	ExpectedValid bool           `json:"expectedValid"`
}

TestCase represents a single test case

func LoadTestCases

func LoadTestCases(filename string) ([]TestCase, error)

LoadTestCases loads test cases from a JSON file in the testdata directory

type TestCaseFile

type TestCaseFile struct {
	TestCases []TestCase `json:"testCases"`
}

TestCaseFile represents a file containing multiple test cases

type ValidationError

type ValidationError struct {
	Path    string
	Message string
}

ValidationError represents a validation error with a path to the field

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationResult

type ValidationResult struct {
	Valid  bool
	Errors []*ValidationError
}

ValidationResult contains the result of validation

func Validate

func Validate(data any, spec *Spec) *ValidationResult

Validate validates a JSON value against a spec

func ValidateAndConvert

func ValidateAndConvert[T any](data any, spec *Spec) (*ValidationResult, T, error)

ValidateAndConvert validates data and converts it to the target type This is a convenience function that combines validation and conversion

func ValidateJSON

func ValidateJSON(jsonData []byte, spec *Spec) (*ValidationResult, error)

ValidateJSON validates a JSON byte slice against a spec

func ValidateJSONString

func ValidateJSONString(jsonStr string, spec *Spec) (*ValidationResult, error)

ValidateJSONString validates a JSON string against a spec

func ValidateStruct

func ValidateStruct[T any](data any, specJSON ...string) (*ValidationResult, T, error)

ValidateStruct validates data against a struct type and returns a typed result T is the struct type to validate against data is the raw data (map[string]any or compatible) specJSON is an optional JSON spec that will be merged on top of the struct-generated spec

func ValidateStructValue

func ValidateStructValue[T any](structValue T, data any, specJSON ...string) (*ValidationResult, T, error)

ValidateStructValue validates data against a struct value (empty instance) and returns a typed result structValue should be an empty struct instance like MyStruct{} data is the raw data (map[string]any or compatible) specJSON is an optional JSON spec that will be merged on top of the struct-generated spec

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址