schema

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: May 28, 2024 License: MIT Imports: 8 Imported by: 0

README

Validator-go


Zod inspired schema validation in Go.


CI Test Status License

Table of contents

Introduction

validator-go is a simple and extensible validation library for Go. It's heavily inspired by Zod and shares a lot of the same interfaces. This library provides a set of validation schemas for different data types, such as integers, strings, and booleans, and allows you to refine these schemas with custom validation rules.

Installation

Ensure you have Go installed (download). Version 1.21 or higher is required.

go get -u github.com/Jamess-Lucass/validator-go

Basic usage

Creating a string schema

import (
    schema "github.com/Jamess-Lucass/validator-go"
)

// Creating a schema for strings
mySchema := schema.String();

// Parsing
mySchema.Parse("john"); // => *schema.ValidationResult
mySchema.Parse("john").IsValid(); // => true
mySchema.Parse(12).Errors; // => []

mySchema.Parse(12).IsValid(); // => false
mySchema.Parse(12).Errors; // => [{ "path": "", "message": "Expected string, received int" }]

Creating an object schema

import (
    schema "github.com/Jamess-Lucass/validator-go"
)

// Creating a schema for an object
mySchema := schema.Object(map[string]schema.ISchema{
    "Username": schema.String().Min(5),
})

// Parsing
type User struct {
    Username string
}

user1 := User{
    Username: "john_doe",
}

mySchema.Parse(user1).IsValid(); // => true
mySchema.Parse(user1).Errors; // => []

user2 := User{
    Username: "john",
}
mySchema.Parse(user2).IsValid(); // => false
mySchema.Parse(user2).Errors; // => [{ "path": "Firstname","message": "String must contain at least 5 character(s)" }]

Primitives

schema.String()
schema.Int()
schema.Bool()

Literals

john := schema.Literal("john");
four := schema.Literal(4);
trueSchema := schema.Literal(true);

Strings

schema.String().Max(2)
schema.String().Min(2)
schema.String().Length(2)
schema.String().Url()
schema.String().Includes(string)
schema.String().StartsWith(string)
schema.String().EndsWith(string)

Ints

schema.Int().Lt(2)
schema.Int().Lte(2)
schema.Int().Gt(2)
schema.Int().Gte(2)

schema.Int().Positive() // > 0
schema.Int().Nonnegative() // >= 0
schema.Int().Negative() // < 0
schema.Int().Nonpositive() // <= 0

schema.Int().MultipleOf(2)

Float64

The same methods are available on Float64 as ints

Booleans

schema.Bool()

Objects

mySchema := schema.Object(map[string]schema.ISchema{
    "Username": schema.String().Min(5),
    "Firstname": schema.String().Min(2).Max(128),
    "Age": schema.Int().Gte(18),
    "IsVerified": schema.Bool(),
})

Arrays

The array schema accepts any type that implements the ISchema interface, this allows you to parse in other schema.

mySchema := schema.Array(schema.String().Min(2)).Max(4)

The above schema defines an array of strings, each of which has a minimum length of 2, with the overall array max length of 4.

You may utilize array and object to construct a more advanced schema

mySchema := schema.Object(map[string]schema.ISchema{
    "Username": schema.String().Min(5),
    "Firstname": schema.String().Min(2).Max(128),
    "Age": schema.Int().Gte(18),
    "Addresses": schema.Array(schema.Object(map[string]schema.ISchema{
        "Postcode": schema.String().Min(4).Max(10),
        "Country": schema.String().Length(2),
    })),
})

Schema methods

All schemas contain certain methods.

.Parse

Given any schema, you may call the .Parse method and pass through any data to check it's validity against the schema.

mySchema := schema.String()

mySchema.Parse("john"); // => *schema.ValidationResult

mySchema.Parse("john").IsValid(); // => true
mySchema.Parse(2).Errors; // => []

mySchema.Parse(2).IsValid(); // => false
mySchema.Parse(2).Errors; // => [{ "path": "", "message": "Expected string, received int" }]

.Refine

You may provide custom validation logic with the .Refine method. This method must return true or false to represent whether validation should be considered successful or unsuccessful.

mySchema := schema.String().Refine(func(value string) bool {
    return value == "custom_value"
})

This is helpful if you need to perform some business-level validation. For example, checking a database for some value or making a HTTP request to assert something.

verifiedUserSchema := schema.String().Refine(func(value string) bool {
    // Fetch user from data.
    // ensure `is_verified` field is true.
    return true
})

This may also be used in conjunction with .Object

type User struct {
    Firstname string
    Lastname  string
    Age       int
}

user := User{
    Firstname: "john",
    Lastname:  "doe",
    Age:       10,
}

mySchema := schema.Object(map[string]schema.ISchema{
    "Firstname": schema.String().Refine(func(value string) bool {
        return value == "john" || value == "jane"
    }),
    "Lastname": schema.String().Refine(func(value string) bool {
        return strings.Contains(value, "doe")
    }),
    "Age": schema.Int().Lt(10),
}).Refine(func(value map[string]interface{}) bool {
    if value["Firstname"] == "jane" {
        if age, ok := value["Age"].(int); ok {
            return age < 5
        }
    }

    return true
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArraySchema added in v0.3.0

type ArraySchema struct {
	Schema[[]interface{}]
	// contains filtered or unexported fields
}

func Array added in v0.3.0

func Array(s ISchema) *ArraySchema

func (*ArraySchema) Max added in v0.3.0

func (s *ArraySchema) Max(maxLength int) *ArraySchema

func (*ArraySchema) Min added in v0.3.0

func (s *ArraySchema) Min(minLength int) *ArraySchema

func (*ArraySchema) Parse added in v0.3.0

func (s *ArraySchema) Parse(value any) *ValidationResult

type BoolSchema

type BoolSchema struct {
	Schema[bool]
}

func Bool

func Bool() *BoolSchema

type Float64Schema added in v0.4.0

type Float64Schema struct {
	Schema[float64]
}

func Float64 added in v0.4.0

func Float64() *Float64Schema

func (*Float64Schema) Gt added in v0.4.0

func (s *Float64Schema) Gt(min float64) *Float64Schema

func (*Float64Schema) Gte added in v0.4.0

func (s *Float64Schema) Gte(min float64) *Float64Schema

func (*Float64Schema) Lt added in v0.4.0

func (s *Float64Schema) Lt(min float64) *Float64Schema

func (*Float64Schema) Lte added in v0.4.0

func (s *Float64Schema) Lte(min float64) *Float64Schema

func (*Float64Schema) MultipleOf added in v0.4.0

func (s *Float64Schema) MultipleOf(multiple float64) *Float64Schema

func (*Float64Schema) Negative added in v0.4.0

func (s *Float64Schema) Negative() *Float64Schema

func (*Float64Schema) Nonnegative added in v0.4.0

func (s *Float64Schema) Nonnegative() *Float64Schema

func (*Float64Schema) Nonpositive added in v0.4.0

func (s *Float64Schema) Nonpositive() *Float64Schema

func (*Float64Schema) Positive added in v0.4.0

func (s *Float64Schema) Positive() *Float64Schema

type ISchema

type ISchema interface {
	Parse(value any) *ValidationResult
}

type IntSchema

type IntSchema struct {
	Schema[int]
}

func Int

func Int() *IntSchema

func (*IntSchema) Gt

func (s *IntSchema) Gt(min int) *IntSchema

func (*IntSchema) Gte

func (s *IntSchema) Gte(min int) *IntSchema

func (*IntSchema) Lt

func (s *IntSchema) Lt(min int) *IntSchema

func (*IntSchema) Lte

func (s *IntSchema) Lte(min int) *IntSchema

func (*IntSchema) MultipleOf

func (s *IntSchema) MultipleOf(multiple int) *IntSchema

func (*IntSchema) Negative

func (s *IntSchema) Negative() *IntSchema

func (*IntSchema) Nonnegative

func (s *IntSchema) Nonnegative() *IntSchema

func (*IntSchema) Nonpositive

func (s *IntSchema) Nonpositive() *IntSchema

func (*IntSchema) Positive

func (s *IntSchema) Positive() *IntSchema

type LiteralSchema added in v0.2.0

type LiteralSchema[T any] struct {
	Schema[T]
}

func Literal added in v0.2.0

func Literal[T any](value T) *LiteralSchema[T]

type ObjectSchema

type ObjectSchema struct {
	Schema[map[string]interface{}]
	// contains filtered or unexported fields
}

func Object

func Object(obj map[string]ISchema) *ObjectSchema

func (*ObjectSchema) Parse

func (s *ObjectSchema) Parse(value any) *ValidationResult

func (*ObjectSchema) Refine

func (s *ObjectSchema) Refine(predicate func(map[string]interface{}) bool) *ObjectSchema

type Schema

type Schema[T any] struct {
	// contains filtered or unexported fields
}

func (*Schema[T]) Parse

func (s *Schema[T]) Parse(value any) *ValidationResult

func (*Schema[T]) Refine

func (s *Schema[T]) Refine(predicate func(T) bool) *Schema[T]

type StringSchema

type StringSchema struct {
	Schema[string]
}

func String

func String() *StringSchema

func (*StringSchema) EndsWith

func (s *StringSchema) EndsWith(str string) *StringSchema

func (*StringSchema) Includes

func (s *StringSchema) Includes(str string) *StringSchema

func (*StringSchema) Length

func (s *StringSchema) Length(length int) *StringSchema

func (*StringSchema) Max

func (s *StringSchema) Max(maxLength int) *StringSchema

func (*StringSchema) Min

func (s *StringSchema) Min(minLength int) *StringSchema

func (*StringSchema) StartsWith

func (s *StringSchema) StartsWith(str string) *StringSchema

func (*StringSchema) Url

func (s *StringSchema) Url() *StringSchema

type TimeSchema added in v0.5.0

type TimeSchema struct {
	Schema[time.Time]
}

func Time added in v0.5.0

func Time() *TimeSchema

type UUIDSchema added in v0.2.0

type UUIDSchema struct {
	Schema[uuid.UUID]
}

func UUID added in v0.2.0

func UUID() *UUIDSchema

type ValidationError

type ValidationError struct {
	Path    string `json:"path"`
	Message string `json:"message"`
}

func (*ValidationError) Error

func (m *ValidationError) Error() string

type ValidationResult

type ValidationResult struct {
	Errors []ValidationError
}

func (*ValidationResult) IsValid

func (v *ValidationResult) IsValid() bool

type Validator

type Validator[T any] struct {
	MessageFunc  func(T) string
	ValidateFunc func(T) bool
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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