validation

package module
v0.0.0-...-251b5ad Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2018 License: MIT Imports: 10 Imported by: 4

README

validation

The Simpler Validation in go.

  • Use func(v interface{}) error for Validater
  • Support User define Validater
  • Support Struct define Validater() error interface
  • Support slice/array/pointer and netestd struct validate. Not for map now!

Build Status Coverage Status GoDoc Go Report Card License MIT

Install and tests

Install:

$go get github.com/DavadDi/validation

Test:

$go test github.com/DavadDi/validation

Simple Usage


package main

import (
	"fmt"

	"github.com/DavadDi/validation"
)

// ex01 simple use
type Person struct {
	Name     string   `valid:"required"`
	Email    string   `valid:"required;email"`
	Age      int      `valid:"-"`
	Sex      int      ``
	WebSites []string `valid:"url"`
}

func main() {
	web1 := "http://www.do1618.com"
	web2 := "www.baidu.com"

	person1 := &Person{
		Name:     "dave",
		Email:    "dwh0403@163.com",
		WebSites: []string{web1, web2},
	}

	validater := validation.NewValidation()
	res := validater.Validate(person1)

	if res {
		fmt.Println("Person1 validate succeed!")
	} else {
		fmt.Printf("Person1 validate failed. %s", validater.ErrMsg())
	}

	validater.Reset()
	person2 := &Person{
		Email:    "dwh0403@163.com",
		WebSites: []string{web1, web2},
	}

	res = validater.Validate(person2)

	if !res {
		fmt.Printf("Person2 validate failed. %s\n", validater.ErrMsg())
	} else {
		fmt.Println("Person2 validate succeed!")
	}
}
Struct Tag Functions:
required
email
url
Output:
Person1 validate succeed!
Person2 validate failed. [Name] check failed [field can't be empty or zero] [""]

Add Use Define Validater

Use define validater func(v interface{}) error and add it to validation.

package main

import (
	"fmt"

	"github.com/DavadDi/validation"
)

type Person struct {
	Name     string   `valid:"required"`
	Email    string   `valid:"required;email"`
	Age      int      `valid:"required;age"`
	Sex      int      ``
	WebSites []string `valid:"url"`
}

func ageChecker(v interface{}) error {
	age, ok := v.(int)
	if !ok {
		return validation.NewErrWrongType("int", v)
	}

	if age <= 0 || age > 140 {
		return fmt.Errorf("age checke failed. should between [1-140], now %d", age)
	}

	return nil
}

func main() {
	validation.AddValidater("age", ageChecker)

	person1 := &Person{
		Name:  "dave",
		Email: "dwh0403@163.com",
	}

	validater := validation.NewValidation()
	res := validater.Validate(person1)

	if res {
		fmt.Println("Person1 validate succeed!")
	} else {
		fmt.Printf("Person1 validate failed. %s\n", validater.ErrMsg())
	}
}

Output:
Person1 validate failed. [Age] check failed [field can't be empty or zero] [0]

Collaborate with Struct Interface

Use struct define validater need impl the interface Validater() error.


package main

import (
	"fmt"
	"log"

	"github.com/DavadDi/validation"
)

type Person struct {
	Name     string `valid:"required"`
	Email    string `valid:"required;email"`
	Age      int
	Sex      int
	WebSites []string `valid:"url"`
}

func (p *Person) Validater() error {
	log.Println("In our struct validater now")
	if p.Age <= 0 || p.Age > 140 {
		return fmt.Errorf("age checke failed. should between [1-140], now %d", p.Age)
	}

	return nil
}

func main() {
	// Turn on debug
	// validation.EnableDebug(true)
	person1 := &Person{
		Name:  "dave",
		Email: "dwh0403@163.com",
	}

	validater := validation.NewValidation()
	res := validater.Validate(person1)

	if res {
		fmt.Println("Person1 validate succeed!")
	} else {
		fmt.Printf("Person1 validate failed. %s\n", validater.ErrMsg())
	}
}


Output
2017/02/28 10:29:34 In our struct validater now
Person1 validate failed. [Object] check failed [age checke failed. should between [1-140], now 0] [&main.Person{Name:"dave", Email:"dwh0403@163.com", Age:0, Sex:0, WebSites:[]string(nil)}]

Check Ptr Field for Requried


package main

import (
	"fmt"

	"github.com/DavadDi/validation"
)

func Bool(a bool) *bool {
	return &a
}

type Person struct {
	Name     string `valid:"required"`
	Email    string `valid:"required;email"`
	Age      int
	Sex      int
	IsAdmin  *bool    `valid:"required"`  // check IsAmdin has or not
	WebSites []string `valid:"url"`
}

func main() {
	// Turn on debug
	validation.EnableDebug(true)
	person1 := &Person{
		Name:  "dave",
		Email: "dwh0403@163.com",

		IsAdmin: Bool(false),
	}

	validater := validation.NewValidation()
	res := validater.Validate(person1)

	if res {
		fmt.Println("Person1 validate succeed!")
	} else {
		fmt.Printf("Person1 validate failed. %s\n", validater.ErrMsg())
	}
}

Why used *IsAdmin bool, because sometime, we recv data from RESTFUL interface, for example:

web pass json struct:

{
   "name": "dave"
}

In go program, we define the struct below, need the both value name && isAdmin

type Person struct {
   Name     *string `valid:"required" json:"name"`
   IsAdmin  *bool    `valid:"required" json:"isAdmin"` 
}

After call json.Marshal, valid required on field ptr can meet the situation.

Debug

Turn on Debug

validation.EnableDebug(true)

Turn off Debug

validation.EnableDebug(false)

LICENSE

MIT License https://choosealicense.com/licenses/mit/ More See https://choosealicense.com/licenses/

Documentation

Overview

Package validation implements a simple library for struct tag validte.

  1. Use interface for Validater
  2. Support User define Validater
  3. Support Struct define validater interface
  4. Support slice/array/pointer and netestd struct validate. Not for map now!

Index

Constants

View Source
const (
	Email      string = "" /* 1212-byte string literal not displayed */
	CreditCard string = "" /* 151-byte string literal not displayed */

	Alpha          string = "^[a-zA-Z]+$"
	Alphanumeric   string = "^[a-zA-Z0-9]+$"
	Numeric        string = "^[-+]?[0-9]+$"
	Int            string = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
	Float          string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
	Hexadecimal    string = "^[0-9a-fA-F]+$"
	Hexcolor       string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
	RGBcolor       string = "" /* 157-byte string literal not displayed */
	ASCII          string = "^[\x00-\x7F]+$"
	Multibyte      string = "[^\x00-\x7F]"
	FullWidth      string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	HalfWidth      string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
	Base64         string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
	PrintableASCII string = "^[\x20-\x7E]+$"
	DataURI        string = "^data:.+\\/(.+);base64$"

	DNSName string = `^([a-zA-Z0-9]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9]{1}[a-zA-Z0-9_-]{1,62})*$`
	IP      string = `` /* 659-byte string literal not displayed */

	URLSchema    string = `((ftp|tcp|udp|wss?|https?):\/\/)`
	URLUsername  string = `(\S+(:\S*)?@)`
	Hostname     string = ``
	URLPath      string = `((\/|\?|#)[^\s]*)`
	URLPort      string = `(:(\d{1,5}))`
	URLIP        string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
	URLSubdomain string = `((www\.)|([a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*))`
	URL          string = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))` + URLPort + `?` + URLPath + `?$`
)

From https://github.com/asaskevich/govalidator/blob/master/patterns.go

View Source
const (
	ValidTag      = "valid"    // Validater tag name
	FuncSeparator = ";"        // Func sparator "required;email"
	ValidIgnor    = "-"        // Igore for validater
	RequiredKey   = "required" // required key for not empty value
)

Global var for validation pkg

Variables

View Source
var (
	ErrBadURLFormat     = errors.New("url format is not valid")
	ErrBadEmailFormat   = errors.New("email format is not valid")
	ErrRequired         = errors.New("field can't be empty or zero")
	ErrValidater        = errors.New("validater should not be nil")
	ErrValidaterNoFound = errors.New("validater not found")
	ErrValidaterExists  = errors.New("validater exist")
)

Error for Validater

Functions

func AddValidater

func AddValidater(name string, validater ValidaterFunc) error

AddValidater Function export to add user define Validater

func EnableDebug

func EnableDebug(flag bool)

EnableDebug enable validation debug log

func NewErrWrongType

func NewErrWrongType(expect string, value interface{}) error

NewErrWrongType new error for unmatched type

Types

type CustomValidators

type CustomValidators struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

CustomValidators Because user can add user define validater, avoid data race, add rwlock

func (*CustomValidators) AddValidater

func (cvm *CustomValidators) AddValidater(name string, validater ValidaterFunc) error

AddValidater If name conflict with CustomValidators, replace. conflict with validatorsMap, return err

type ErrOnlyStrcut

type ErrOnlyStrcut struct {
	Type reflect.Type
}

ErrOnlyStrcut only for validate struct

func (*ErrOnlyStrcut) Error

func (err *ErrOnlyStrcut) Error() string

ErrOnlyStrcut detail error msg

type ErrUnsupportedType

type ErrUnsupportedType struct {
	Type reflect.Type
}

ErrUnsupportedType not support type

func (*ErrUnsupportedType) Error

func (err *ErrUnsupportedType) Error() string

type ErrWrongExpectType

type ErrWrongExpectType struct {
	ExpectType string
	PassValue  interface{}
}

ErrWrongExpectType expect type don't match passed type

func (*ErrWrongExpectType) Error

func (err *ErrWrongExpectType) Error() string

ErrWrongExpectType detail error

type Error

type Error struct {
	FieldName string
	Value     interface{}
	Err       error
}

Error for Validator, including filedname, value, err msg.

func (*Error) String

func (err *Error) String() string

type Validater

type Validater interface {
	Validater() error
}

Validater Interface For use define stuct, without params If validate struct has this interface, we will call this interface firstly

type ValidaterFunc

type ValidaterFunc func(v interface{}) error

ValidaterFunc type

type Validation

type Validation struct {
	Errors []*Error
}

Validation err list

func NewValidation

func NewValidation() *Validation

NewValidation create a new validation

func (*Validation) ErrMsg

func (mv *Validation) ErrMsg() string

ErrMsg Return msg detail Error message

func (*Validation) Errs

func (mv *Validation) Errs() []*Error

Errs Return Error list

func (*Validation) HasError

func (mv *Validation) HasError() bool

HasError Check has errors or not

func (*Validation) Reset

func (mv *Validation) Reset()

Reset reset state to init

func (*Validation) Validate

func (mv *Validation) Validate(obj interface{}) bool

Validate entry function. True: Validiton passed. False: Validate don't passed, mv.ErrMsg() contains the detail info.

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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