validator

package module
v0.0.0-...-9e0331a Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2017 License: MIT Imports: 11 Imported by: 0

README

Validator

Package validator implements value validation for struct fields.

The package was a fork of go-validator but was rewritten to:

  • Reduce unneccesary memory allocations
  • Support Slice/Array, Map, Interface,
  • Simplify source code.

Download

go get github.com/predixdeveloperACN/validator

Example

package main

import (
	"errors"
	"fmt"

	"github.com/predixdeveloperACN/validator"
)

type User struct {
	Name      string     `valid:"notempty"`
	Age       int        `valid:"min=13"`
	Addresses []*Address `valid:"min=1,max=2"`
	BirthDay  string     `valid:"date=MMDDYYYY"`
	Phone     int        `valid:"regex=^[0-9]*$"`
}

type Address struct {
	Line1    string
	Line2    string
	PostCode int    `valid:"min=1"`
	Country  string `valid:"notempty,max=2"`
}

func (a *Address) Validate() error {
	if a.Line1 == "" && a.Line2 == "" {
		return errors.New("Either address Line1 or Line2 must be set")
	}
	return nil
}

func main() {
	u := &User{
		Addresses: []*Address{
			&Address{
				Line1:    "Somewhere",
				PostCode: 1000,
				Country:  "AU",
			},
			&Address{
				PostCode: -1,
				Country:  "US",
			},
			&Address{
				Line2:    "Here",
				PostCode: 1,
				Country:  "USA",
			},
		},
	}
	v := validator.Default()
	fmt.Println(v.Validate(u))
	// Output:
	// Name must not be empty,
	// Age must not be less than 13 (was 0),
	// Addresses must have length not greater than 2 (was 3),
	// BirthDay is not a valid date,
	// Either address Line1 or Line2 must be set,
	// PostCode must not be less than 1 (was -1),
	// Country must have length not greater than 2 (was 3)
}

Date Validator Placeholders

M    - month (1)
MM   - month (01)
MMM  - month (Jan)
MMMM - month (January)
D    - day (2)
DD   - day (02)
DDD  - day (Mon)
DDDD - day (Monday)
YY   - year (06)
YYYY - year (2006)
hh   - hours (15)
mm   - minutes (04)
ss   - seconds (05)

AM/PM hours: 'h' followed by optional 'mm' and 'ss' followed by 'pm', e.g.

hpm        - hours (03PM)
h:mmpm     - hours:minutes (03:04PM)
h:mm:sspm  - hours:minutes:seconds (03:04:05PM)

Time zones: a time format followed by 'ZZZZ', 'ZZZ' or 'ZZ', e.g.

hh:mm:ss ZZZZ (16:05:06 +0100)
hh:mm:ss ZZZ  (16:05:06 CET)
hh:mm:ss ZZ   (16:05:06 +01:00)

Documentation

Overview

Package validator provides validation for structs and fields.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Errors

type Errors []error

Errors is a list of error.

func (Errors) Error

func (e Errors) Error() string

Error returns formatted string of all underlying errors.

type Func

type Func func(v reflect.Value, name, param string) error

Func validates field with value v, field name and parameter p.

type Option

type Option func(v *Validator)

Option sets options for the validator.

func DefaultOption

func DefaultOption() Option

DefaultOption returns an Option which sets validator to use tag name 'valid' and support function 'notempty', 'min', 'max'.

func WithFunc

func WithFunc(name string, fn Func) Option

WithFunc returns an Option which adds a new function handler. If a function with same name existed, it will be overriden by the given one. It panics if name is empty or handler is nil.

func WithTagName

func WithTagName(tagName string) Option

WithTagName returns an Option which sets tagName to the validator.

type UnsupportedError

type UnsupportedError string

UnsupportedError is a generic error returned when validation function is applied on fields it does not support or the function has not been registered to Validator.

func (UnsupportedError) Error

func (e UnsupportedError) Error() string

type Validatable

type Validatable interface {
	Validate() error
}

Validatable is an interface implemented by types that can validate themselves.

type Validator

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

Validator implements value validation for structs and fields.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/predixdeveloperACN/validator"
)

type User struct {
	Name      string     `valid:"notempty"`
	Age       int        `valid:"min=13"`
	Addresses []*Address `valid:"min=1,max=2"`
}

type Address struct {
	Line1    string
	Line2    string
	PostCode int    `valid:"min=1"`
	Country  string `valid:"notempty,max=2"`
}

func (a *Address) Validate() error {
	if a.Line1 == "" && a.Line2 == "" {
		return errors.New("Either address Line1 or Line2 must be set")
	}
	return nil
}

func main() {
	u := User{
		Addresses: []*Address{
			&Address{
				Line1:    "Somewhere",
				PostCode: 1000,
				Country:  "AU",
			},
			&Address{
				PostCode: -1,
				Country:  "US",
			},
			&Address{
				Line2:    "Here",
				PostCode: 1,
				Country:  "USA",
			},
		},
	}
	v := validator.Default()
	fmt.Println(v.Validate(&u))
}
Output:

Name must not be empty,
Age must not be less than 13 (was 0),
Addresses must have length not greater than 2 (was 3),
Either address Line1 or Line2 must be set,
PostCode must not be less than 1 (was -1),
Country must have length not greater than 2 (was 3)

func Default

func Default() *Validator

Default returns a new default validator. See DefaultOption for the options used for the validator.

func New

func New(options ...Option) *Validator

New allocates and returns a new Validator with given options. To create a new Validator with default options, use Default instead.

func (*Validator) Validate

func (a *Validator) Validate(v interface{}) (err error)

Validate validates given value. Value v is usually a pointer to the struct to validate, but it can also be a struct, slice or array.

Jump to

Keyboard shortcuts

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