check

package module
v0.0.0-...-d71bc79 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2019 License: MIT Imports: 6 Imported by: 8

README

check - Go package for data validation

Build Status GoDoc

Design goals

  • Composite pattern
  • Multiple constraints on the same value by applying multiple validators
  • Easy to create custom validators
  • Easy to customize error messages

Usage

go get github.com/pengux/check

To run tests:

cd $GOPATH/src/github.com/pengux/check && go test

To validate your data, create a new Struct and add validators to it:

type User struct {
	Username string
}

func main() {
	u := &User{
		Username: "invalid*",
	}

	s := check.Struct{
		"Username": check.Composite{
			check.NonEmpty{},
			check.Regex{`^[a-zA-Z0-9]+$`},
			check.MinChar{10},
		},
	}

	e := s.Validate(u)

	if e.HasErrors() {
		err, ok := e.GetErrorsByKey("Username")
		if !ok {
			panic("key 'Username' does not exists")
		}
		fmt.Println(err)
	}
}

To use your own custom validator, just implement the Validator interface:

type CustomStringContainValidator struct {
	Constraint string
}

func (validator CustomStringContainValidator) Validate(v interface{}) check.Error {
	if !strings.Contains(v.(string), validator.Constraint) {
		return check.NewValidationError("customStringContainValidator", v, validator.Constraint)
	}

	return nil
}

func main() {
	username := "invalid*"
	validator := CustomStringContainValidator{"admin"}
	e := validator.Validate(username)
	fmt.Println(check.ErrorMessages[e.Error()])
}

To use custom error messages, either overwrite the package variable ErrorMessages or create your own map[string]string:

check.ErrorMessages["minChar"] := "the string must be minimum %v characters long"
errMessages := errs.ToMessages()
fmt.Println(errMessages)

For more example code check the file e2e_test.go.

Documentation

Overview

Package check allows data validation of values in different types

Example
package main

import "fmt"

type Person struct {
	Name string
}

func main() {
	p := &Person{
		Name: "invalid*",
	}

	s := Struct{
		"Name": Composite{
			NonEmpty{},
			Regex{`^[a-zA-Z0-9]+$`},
			MinChar{10},
		},
	}

	e := s.Validate(*p)

	if e.HasErrors() {
		err, ok := e.GetErrorsByKey("Name")
		if !ok {
			panic("key 'Name' does not exists")
		}
		fmt.Println(err)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrorMessages contains default error messages
	ErrorMessages = map[string]string{
		"nonZero":     "value cannot be empty",
		"before":      "%v is not before %v",
		"after":       "%v is not after %v",
		"lowerThan":   "%v is not lower than %v",
		"greaterThan": "%v is not greater than %v",
		"minChar":     "too short, minimum %v characters",
		"maxChar":     "too long, minimum %v characters",
		"email":       "'%v' is an invalid email address",
		"regex":       "'%v' does not match '%v'",
		"uuid":        "'%v' is an invalid uuid",
	}
)

Functions

This section is empty.

Types

type After

type After struct {
	Constraint time.Time
}

After check if a time in Value is before the time in Constraint

func (After) Validate

func (validator After) Validate(v interface{}) Error

Validate check if a time in Value is after the time in Constraint

type Before

type Before struct {
	Constraint time.Time
}

Before check if a time in Value is before the time in Constraint

func (Before) Validate

func (validator Before) Validate(v interface{}) Error

Validate check if a time in Value is before the time in Constraint

type Composite

type Composite []Validator

Composite allows adding multiple validators to the same value

func (Composite) Validate

func (c Composite) Validate(v interface{}) Error

Validate implements Validator

type Email

type Email struct{}

Email is a constraint to do a simple validation for email addresses, it only check if the string contains "@" and that it is not in the first or last character of the string. Also if there is only one "@" and if there is a "." in the string after the "@".

func (Email) Validate

func (validator Email) Validate(v interface{}) Error

Validate email addresses

type Error

type Error interface {
	Error() string
	ErrorMap() map[string][]interface{}
}

Error is the default validation error. The Params() method returns the params to be used in error messages

type GreaterThan

type GreaterThan struct {
	Constraint float64
}

GreaterThan validates that a number must be greater than its value

func (GreaterThan) Validate

func (validator GreaterThan) Validate(v interface{}) Error

Validate check value against constraint

type LowerThan

type LowerThan struct {
	Constraint float64
}

LowerThan validates that a number must be lower than its value

func (LowerThan) Validate

func (validator LowerThan) Validate(v interface{}) Error

Validate check value against constraint

type MaxChar

type MaxChar struct {
	Constraint int
}

MaxChar validates that a string must have a length maximum of its constraint

func (MaxChar) Validate

func (validator MaxChar) Validate(v interface{}) Error

Validate check value against constraint

type MinChar

type MinChar struct {
	Constraint int
}

MinChar validates that a string must have a length minimum of its constraint

func (MinChar) Validate

func (validator MinChar) Validate(v interface{}) Error

Validate check value against constraint

type NonEmpty

type NonEmpty struct{}

NonEmpty check that the value is not a zeroed value depending on its type

func (NonEmpty) Validate

func (validator NonEmpty) Validate(v interface{}) Error

Validate value to not be a zeroed value, return error and empty slice of strings

type Regex

type Regex struct {
	Constraint string
}

Regex allow validation usig regular expressions

func (Regex) Validate

func (validator Regex) Validate(v interface{}) Error

Validate using regex

type Slice

type Slice struct {
	Inner Validator
}

func (Slice) Validate

func (c Slice) Validate(v interface{}) Error

type Struct

type Struct map[string]Validator

Struct allows validation of structs

func (Struct) Validate

func (s Struct) Validate(v interface{}) StructError

Validate execute validation using the validators.

type StructError

type StructError map[string][]Error

StructError is a map with validation errors

func (StructError) Error

func (e StructError) Error() string

Error satisfy error interface. Will return a concatenated strings of errors separated by "\n"

func (StructError) GetErrorsByKey

func (e StructError) GetErrorsByKey(key string) ([]Error, bool)

GetErrorsByKey return all errors for a specificed key

func (StructError) HasErrors

func (e StructError) HasErrors() bool

HasErrors return true if the ErrorMap has errors

func (StructError) ToMessages

func (e StructError) ToMessages() map[string]map[string]string

ToMessages convert StructError to a map of field and their validation key with proper error messages

type UUID

type UUID struct{}

UUID verify a string in the UUID format xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

func (UUID) Validate

func (validator UUID) Validate(v interface{}) Error

Validate checks a string as correct UUID format

type ValidationError

type ValidationError struct {
	// contains filtered or unexported fields
}

ValidationError implements Error

func NewValidationError

func NewValidationError(key string, params ...interface{}) *ValidationError

NewValidationError create and return a ValidationError

func (ValidationError) Error

func (e ValidationError) Error() string

func (ValidationError) ErrorMap

func (e ValidationError) ErrorMap() map[string][]interface{}

ErrorMap returns the error map

type Validator

type Validator interface {
	// Validate check value against constraints
	Validate(v interface{}) Error
}

Validator is an interface for constraint types with a method of validate()

Example
username := "invalid*"
validator := CustomStringContainValidator{"admin"}
e := validator.Validate(username)
fmt.Println(ErrorMessages[e.Error()])
Output:

Jump to

Keyboard shortcuts

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