go-validator: github.com/choria-io/go-validator Index | Examples | Files | Directories

package validator

import "github.com/choria-io/go-validator"

Package validator provides common validation helpers commonly used in operations tools. Additionally structures can be marked up with tags indicating the validation of individual keys and the entire struct can be validated in one go

Code:

valid := []string{"one", "two", "three"}

ok, err := enum.ValidateSlice([]string{"one", "two"}, valid)
if !ok {
    panic(err)
}

fmt.Println("slice 1 is valid")

ok, err = enum.ValidateSlice([]string{"5", "6"}, valid)
if !ok {
    fmt.Println("slice 2 is invalid")
}

// string is valid
ok, err = enum.ValidateString("one", valid)
if !ok {
    panic(err)
}

fmt.Println("string is valid")

Output:

slice 1 is valid
slice 2 is invalid
string is valid

Code:

ok, err := maxlength.ValidateString("a short string", 20)
if !ok {
    panic(err)
}

fmt.Println("string validates")

Output:

string validates

Code:

// a sell safe command, unsafe might be `un > safe`
ok, err := shellsafe.Validate("safe")
if !ok {
    panic(err)
}

fmt.Printf("string is safe")

Output:

string is safe

Code:

package main

import (
    "fmt"

    validator "github.com/choria-io/go-validator"
)

type Request struct {
    Command string   `validate:"shellsafe"`
    Flags   []string `validate:"enum=debug,verbose"`
    Args    string   `validate:"maxlength=128"`
    AnyIP   string   `validate:"ipaddress"` // can also check ipv4 and ipv6
    User    string   `validate:"regex=^\\w+$"`
}

func main() {
    r := Request{
        Command: "/bin/some/command",
        Flags:   []string{"debug"},
        Args:    "hello world",
        AnyIP:   "2a00:1450:4003:807::200e",
        User:    "bob",
    }

    ok, err := validator.ValidateStruct(r)
    if !ok {
        panic(err)
    }

    fmt.Println("valid request")

    ok, err = validator.ValidateStructField(r, "Command")
    if !ok {
        panic(err)
    }

    fmt.Println("valid field")

}

Index

Examples

Package Files

validator.go

func ValidateStruct Uses

func ValidateStruct(target interface{}) (bool, error)

ValidateStruct validates all keys in a struct using their validate tag

func ValidateStructField Uses

func ValidateStructField(target interface{}, field string) (bool, error)

ValidateStructField validates one field in a struct

Directories

PathSynopsis
duration
enum
ipaddress
ipv4
ipv6
maxlength
regex
shellsafe

Package validator imports 11 packages (graph) and is imported by 2 packages. Updated 2018-06-10. Refresh now. Tools for package owners.