validation

package
v0.0.0-...-1eb86f4 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2019 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package validation provides input validation for resources.

Example (Builtin)
package main

import (
	"fmt"

	"github.com/func/func/resource/validation"
)

func main() {
	v := validation.New()
	validation.AddBuiltin(v)

	tag := "min=5,max=6"

	fmt.Println(v.Validate("bar", tag))
	fmt.Println(v.Validate("foobar", tag))
	fmt.Println(v.Validate("foobarbaz", tag))
}
Output:

length must be at least 5 characters
<nil>
length must be at most 6 characters
Example (CustomFunc)
package main

import (
	"fmt"

	"github.com/func/func/resource/validation"
)

func main() {
	v := validation.New()

	v.Add("eq", func(value interface{}, param string) error {
		str := fmt.Sprintf("%v", value)
		if str != param {
			return fmt.Errorf("value must be %q", param)
		}
		return nil
	})

	fmt.Println(v.Validate("bar", "eq=foo"))
	fmt.Println(v.Validate("foo", "eq=foo"))
}
Output:

value must be "foo"
<nil>

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddBuiltin

func AddBuiltin(validator *Validator)

AddBuiltin add built in common validators.

Types

type InvalidRuleError

type InvalidRuleError struct {
	Reason string
}

An InvalidRuleError is returned when the rule cannot be processed. This indicates a programmer error, rather than user error.

func (InvalidRuleError) Error

func (e InvalidRuleError) Error() string

type Validator

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

A Validator maintains a list of registered validation rules.

func New

func New() *Validator

New creates a new empty validator. Rules should be added to the validator with Add().

func (*Validator) Add

func (v *Validator) Add(name string, rule func(value interface{}, param string) error)

Add registers a new validation rule.

Not safe for concurrent access.

Panics if a validator with the same name has already been registered.

func (*Validator) Validate

func (v *Validator) Validate(value interface{}, rules string) error

Validate validates the given input value against rules.

Rules must be provided in a comma separated list (without space):

rule1,rule2

Additional parameters can be provided to rules:

min=3,max=10

If rules is empty, no validation is performed.

Jump to

Keyboard shortcuts

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