validating: github.com/RussellLuo/validating Index | Examples | Files

package validating

import "github.com/RussellLuo/validating"

Code:

package main

import (
    "fmt"
    "time"

    v "github.com/RussellLuo/validating"
)

func validate(field v.Field) v.Errors {
    switch t := field.ValuePtr.(type) {
    case *map[string]time.Time:
        if *t == nil {
            return v.NewErrors(field.Name, v.ErrInvalid, "is empty")
        }
        return nil
    default:
        return v.NewErrors(field.Name, v.ErrUnsupported, "is unsupported")
    }
}

type MyValidator struct{}

func (mv *MyValidator) Validate(field v.Field) v.Errors {
    return validate(field)
}

func main() {
    var value map[string]time.Time

    // do validation by funcValidator
    funcValidator := v.FromFunc(func(field v.Field) v.Errors {
        return validate(field)
    })
    errs := v.Validate(v.Schema{
        v.F("value", &value): funcValidator,
    })
    fmt.Printf("errs from funcValidator: %+v\n", errs)

    // do validation by structValidator
    structValidator := &MyValidator{}
    errs = v.Validate(v.Schema{
        v.F("value", &value): structValidator,
    })
    fmt.Printf("errs from structValidator: %+v\n", errs)
}

Code:

// import "flag"
// import "fmt"
// import v "github.com/RussellLuo/validating"

value := flag.String("value", "", "Value argument")
flag.Parse()

err := v.Validate(v.Schema{
    v.F("value", value): v.All(v.Nonzero(), v.Len(2, 5)),
})
fmt.Printf("err: %+v\n", err)

Output:

err: value: INVALID(is zero valued)

Code:

package main

import (
    "fmt"

    v "github.com/RussellLuo/validating"
)

type Address struct {
    Country, Province, City string
}

type Person struct {
    Name    string
    Age     int
    Address Address
}

func main() {
    p := Person{}
    err := v.Validate(v.Schema{
        v.F("name", &p.Name): v.Len(1, 5),
        v.F("age", &p.Age):   v.Gte(10),
        v.F("address", &p.Address): v.Nested(v.Schema{
            v.F("country", &p.Address.Country):  v.Nonzero(),
            v.F("province", &p.Address.Country): v.Nonzero(),
            v.F("city", &p.Address.City):        v.Nonzero(),
        }),
    })
    fmt.Printf("err: %+v\n", err)
}

Code:

package main

import (
    "fmt"

    v "github.com/RussellLuo/validating"
)

type Member struct {
    Name string
}

type Person1 struct {
    Name   string
    Age    int
    Family map[string]*Member
}

func makeSchema1(p *Person1) v.Schema {
    return v.Schema{
        v.F("name", &p.Name): v.Len(1, 5),
        v.F("age", &p.Age):   v.Nonzero(),
        v.F("family", &p.Family): v.All(
            v.Assert(p.Family != nil, "is empty"),
            v.NestedMulti(func() (schemas []v.Schema) {
                for relation, member := range p.Family {
                    schemas = append(schemas, v.Schema{
                        v.F(fmt.Sprintf("[%s].name", relation), &member.Name): v.Len(10, 15, "is too long"),
                    })
                }
                return
            }),
        ),
    }
}

func main() {
    p1 := Person1{}
    err := v.Validate(makeSchema1(&p1))
    fmt.Printf("err of p1: %+v\n", err)

    p2 := Person1{Family: map[string]*Member{
        "father": {"father's name"},
        "mother": {"mother's name is long"},
    }}
    err = v.Validate(makeSchema1(&p2))
    fmt.Printf("err of p2: %+v\n", err)
}

Code:

package main

import (
    "fmt"

    v "github.com/RussellLuo/validating"
)

type Address2 struct {
    Country, Province, City string
}

type Person2 struct {
    Name    string
    Age     int
    Address *Address2
}

func makeSchema2(p *Person2) v.Schema {
    return v.Schema{
        v.F("name", &p.Name): v.Len(1, 5),
        v.F("age", &p.Age):   v.Lte(50),
        v.F("address", &p.Address): v.All(
            v.Assert(p.Address != nil, "is nil"),
            v.Lazy(func() v.Validator {
                return v.Nested(v.Schema{
                    v.F("country", &p.Address.Country):  v.Nonzero(),
                    v.F("province", &p.Address.Country): v.Nonzero(),
                    v.F("city", &p.Address.City):        v.Nonzero(),
                })
            }),
        ),
    }
}

func main() {
    p1 := Person2{}
    err := v.Validate(makeSchema2(&p1))
    fmt.Printf("err of p1: %+v\n", err)

    p2 := Person2{Age: 60, Address: &Address2{}}
    err = v.Validate(makeSchema2(&p2))
    fmt.Printf("err of p2: %+v\n", err)
}

Code:

package main

import (
    "fmt"

    v "github.com/RussellLuo/validating"
)

type Address3 struct {
    Country, Province, City string
}

func (a *Address3) Schema() v.Schema {
    return v.Schema{
        v.F("country", &a.Country):  v.Nonzero(),
        v.F("province", &a.Country): v.Nonzero(),
        v.F("city", &a.City):        v.Nonzero(),
    }
}

type Person3 struct {
    Name    string
    Age     int
    Address Address3
}

func (p *Person3) Schema() v.Schema {
    return v.Schema{
        v.F("name", &p.Name):       v.Len(1, 5),
        v.F("age", &p.Age):         v.Gte(10),
        v.F("address", &p.Address): v.Nested(p.Address.Schema()),
    }
}

func main() {
    p := Person3{}
    err := v.Validate(p.Schema())
    fmt.Printf("err: %+v\n", err)
}

Code:

package main

import (
    "fmt"

    v "github.com/RussellLuo/validating"
)

type Phone struct {
    Number, Remark string
}

type Person4 struct {
    Name   string
    Age    int
    Phones []*Phone
}

func makeSchema4(p *Person4) v.Schema {
    return v.Schema{
        v.F("name", &p.Name): v.Len(1, 5),
        v.F("age", &p.Age):   v.Nonzero(),
        v.F("phones", &p.Phones): v.All(
            v.Assert(p.Phones != nil, "is empty"),
            v.NestedMulti(func() (schemas []v.Schema) {
                for i, phone := range p.Phones {
                    schemas = append(schemas, v.Schema{
                        v.F(fmt.Sprintf("[%d].number", i), &phone.Number): v.Nonzero(),
                        v.F(fmt.Sprintf("[%d].remark", i), &phone.Remark): v.Len(5, 7),
                    })
                }
                return
            }),
        ),
    }
}

func main() {
    p1 := Person4{}
    err := v.Validate(makeSchema4(&p1))
    fmt.Printf("err of p1: %+v\n", err)

    p2 := Person4{Phones: []*Phone{
        {"13011112222", "private"},
        {"13033334444", "business"},
    }}
    err = v.Validate(makeSchema4(&p2))
    fmt.Printf("err of p2: %+v\n", err)
}

Code:

package main

import (
    "fmt"

    v "github.com/RussellLuo/validating"
)

type Person5 struct {
    Name string
    Age  int
}

func main() {
    p := Person5{}
    err := v.Validate(v.Schema{
        v.F("name", &p.Name): v.Len(1, 5, "length is not between 1 and 5"),
        v.F("age", &p.Age):   v.Nonzero(),
    })
    fmt.Printf("err: %+v\n", err)
}

Code:

// import "fmt"
// import v "github.com/RussellLuo/validating"

value := 0
err := v.Validate(v.Schema{
    v.F("value", &value): v.Range(1, 5),
})
fmt.Printf("err: %+v\n", err)

Output:

err: value: INVALID(is not between given range)

Index

Examples

Package Files

builtin.go errors.go validating.go

Constants

const (
    ErrUnsupported  = "UNSUPPORTED"
    ErrUnrecognized = "UNRECOGNIZED"
    ErrInvalid      = "INVALID"
)

Variables

var And = All

And is an alias of All.

var Or = Any

Or is an alias of Any.

type Error Uses

type Error interface {
    error
    Field() string
    Kind() string
    Message() string
}

func NewError Uses

func NewError(field, kind, message string) Error

type Errors Uses

type Errors []Error

func NewErrors Uses

func NewErrors(field, kind, message string) (errs Errors)

func Validate Uses

func Validate(schema Schema) Errors

Validate validates fields according to the pre-defined schema.

func (*Errors) Append Uses

func (e *Errors) Append(err Error)

func (Errors) Error Uses

func (e Errors) Error() string

func (*Errors) Extend Uses

func (e *Errors) Extend(errs Errors)

type Field Uses

type Field struct {
    Name     string
    ValuePtr interface{}
}

Field represents a (Name, ValuePtr) pair need to be validated.

func F Uses

func F(name string, valuePtr interface{}) Field

F is a shortcut for creating an instance of Field.

type FromFunc Uses

type FromFunc func(field Field) Errors

FromFunc is an adapter to allow the use of ordinary functions as validators. If f is a function with the appropriate signature, FromFunc(f) is a Validator that calls f.

func (FromFunc) Validate Uses

func (f FromFunc) Validate(field Field) Errors

Validate calls f(field).

type Schema Uses

type Schema map[Field]Validator

Schema is a field mapping, which defines the corresponding validator for each field.

type Validator Uses

type Validator interface {
    Validate(field Field) Errors
}

Validator is an interface for representing a validating's validator.

func All Uses

func All(validators ...Validator) Validator

All is a composite validator factory to create a validator, which will succeed only when all sub-validators succeed.

func Any Uses

func Any(validators ...Validator) Validator

Any is a composite validator factory to create a validator, which will succeed as long as any sub-validator succeeds.

func Assert Uses

func Assert(b bool, msgs ...string) Validator

Assert is a leaf validator factory to create a validator, which will succeed only when the boolean expression evaluates to true.

func Gt Uses

func Gt(value interface{}, msgs ...string) Validator

Gt is a leaf validator factory to create a validator, which will succeed when the field's value is greater than the given value.

func Gte Uses

func Gte(value interface{}, msgs ...string) Validator

Gte is a leaf validator factory to create a validator, which will succeed when the field's value is greater than or equal to the given value.

func In Uses

func In(values ...interface{}) Validator

In is a leaf validator factory to create a validator, which will succeed when the field's value is equal to one of the given values.

func Lazy Uses

func Lazy(f func() Validator) Validator

Lazy is a composite validator factory to create a validator, which will call f only as needed, to delegate the actual validation to the validator returned by f.

func Len Uses

func Len(min, max int, msgs ...string) Validator

Len is a leaf validator factory to create a validator, which will succeed when the field's length is between min and max.

func Lt Uses

func Lt(value interface{}, msgs ...string) Validator

Lt is a leaf validator factory to create a validator, which will succeed when the field's value is lower than the given value.

func Lte Uses

func Lte(value interface{}, msgs ...string) Validator

Lte is a leaf validator factory to create a validator, which will succeed when the field's value is lower than or equal to the given value.

func Nested Uses

func Nested(schema Schema) Validator

Nested is a composite validator factory to create a validator, which will delegate the actual validation to its inner schema.

func NestedMulti Uses

func NestedMulti(f func() []Schema) Validator

NestedMulti is a composite validator factory to create a validator, which will delegate the actual validation to its inner multiple schemas, which are returned by calling f.

func Nonzero Uses

func Nonzero(msgs ...string) Validator

Nonzero is a leaf validator factory to create a validator, which will succeed when the field's value is nonzero.

func Not Uses

func Not(validator Validator, msgs ...string) Validator

Not is a composite validator factory to create a validator, which will succeed when the given validator fails.

func Range Uses

func Range(min, max interface{}, msgs ...string) Validator

Range is a shortcut of `All(Gte(min), Lte(max))`.

func RegexpMatch Uses

func RegexpMatch(re *regexp.Regexp, msgs ...string) Validator

RegexpMatch is a leaf validator factory to create a validator, which will succeed when the field's value matches the given regular expression.

Package validating imports 4 packages (graph). Updated 2020-07-03. Refresh now. Tools for package owners.