validation

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2025 License: MIT Imports: 8 Imported by: 0

README

Validation Package

This Go package provides a flexible framework for validating struct fields using custom rules. It leverages Go's reflection to apply both user-defined and built-in validation rules to struct fields, making it easy to enforce constraints on your data.

Features

  • Customizable Rules: Easily define your own validation functions using the Rule type.
  • Schema-Based Validation: Associate one or more rules with struct fields via a Schema map.
  • Built-in Validators: Includes a variety of common validators:
    • Required field checks
    • String length checks (MaxLen, MinLen, ExactLen)
    • Numeric bounds (MaxValue, MinValue, GreaterThan, LessThan, Between)
    • Regular expression matches, including email, URL, UUID, and more
    • IP address (IPv4/IPv6) validation
    • Date, time, and datetime format validation

Code Structure

  • rule.go:
    Defines the Rule type and provides helper functions to compose multiple rules.

  • schema.go:
    Implements the Schema type and its Validate method, which iterates over struct fields and applies associated validation rules.

  • default_rules.go:
    Contains built-in validation functions for common requirements. These include checks for required values, length constraints, numeric comparisons, regex matching, and specialized validations (like email, URL, IP addresses, dates, etc.).

Installation

Simply add the source files to your project and import the package in your Go code:

import "path/to/validation"

Ensure that the package path reflects the actual location of the code in your project.

Usage Example

Define a struct and a corresponding schema that maps field names to a list of rules:

package main

import (
	"fmt"
	"validation"
)

type User struct {
	Name  string
	Email string
	Age   int
}

func main() {
	// Define validation schema for the User struct
	schema := validation.Schema{
		"Name":  validation.Rules(validation.Required(), validation.MinLen(2)),
		"Email": validation.Rules(validation.Required(), validation.Email()),
		"Age":   validation.Rules(validation.Required(), validation.MinValue(18)),
	}

	user := User{Name: "John Doe", Email: "john@example.com", Age: 25}
	if err := schema.Validate(user); err != nil {
		fmt.Println("Validation error:", err)
	} else {
		fmt.Println("Validation successful!")
	}
}

This example demonstrates how to validate a User struct by ensuring that:

  • The Name field is provided and is at least 2 characters long.
  • The Email field is provided and follows a valid email format.
  • The Age field is provided and is at least 18.

Contributing

Contributions to enhance or expand the validation functionality are welcome. Feel free to fork the repository and submit a pull request with your improvements.

License

This package is distributed under the MIT License. See the LICENSE file for more details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Types = map[reflect.Kind]string{
	reflect.Invalid:       "invalid",
	reflect.Bool:          "bool",
	reflect.Int:           "int",
	reflect.Int8:          "int8",
	reflect.Int16:         "int16",
	reflect.Int32:         "int32",
	reflect.Int64:         "int64",
	reflect.Uint:          "uint",
	reflect.Uint8:         "uint8",
	reflect.Uint16:        "uint16",
	reflect.Uint32:        "uint32",
	reflect.Uint64:        "uint64",
	reflect.Uintptr:       "uintptr",
	reflect.Float32:       "float32",
	reflect.Float64:       "float64",
	reflect.Complex64:     "complex64",
	reflect.Complex128:    "complex128",
	reflect.Array:         "array",
	reflect.Chan:          "chan",
	reflect.Func:          "func",
	reflect.Interface:     "interface",
	reflect.Map:           "map",
	reflect.Pointer:       "pointer",
	reflect.Slice:         "slice",
	reflect.String:        "string",
	reflect.Struct:        "struct",
	reflect.UnsafePointer: "unsafe_pointer",
}

Functions

This section is empty.

Types

type Rule

type Rule func(v any, kind reflect.Kind) error

func Alpha

func Alpha() Rule

func Alphanumeric

func Alphanumeric() Rule

func Between

func Between(min, max float64) Rule

func ContainsDigit

func ContainsDigit() Rule

func ContainsLower

func ContainsLower() Rule

func ContainsSpecial

func ContainsSpecial() Rule

func ContainsUpper

func ContainsUpper() Rule

func Date

func Date() Rule

func DateTime

func DateTime() Rule

func Email

func Email() Rule

func EndsWith

func EndsWith(suffix string) Rule

func ExactLen

func ExactLen(n int) Rule

func GreaterThan

func GreaterThan(n float64) Rule

func IP

func IP() Rule

func IPv4

func IPv4() Rule

func IPv6

func IPv6() Rule

func LessThan

func LessThan(n float64) Rule

func MaxLen

func MaxLen(n int) Rule

func MaxValue

func MaxValue(n float64) Rule

func MinLen

func MinLen(n int) Rule

func MinValue

func MinValue(n float64) Rule

func Numeric

func Numeric() Rule

func RegexMatch

func RegexMatch(pattern string) Rule

func Required

func Required() Rule

func Rules

func Rules(rules ...Rule) []Rule

func StartsWith

func StartsWith(prefix string) Rule

func Time

func Time() Rule

func URL

func URL() Rule

func UUID

func UUID() Rule

type Schema

type Schema map[string][]Rule

func (Schema) Validate

func (s Schema) Validate(v any) error

Jump to

Keyboard shortcuts

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