ecms_validator

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2019 License: BSD-3-Clause Imports: 4 Imported by: 1

README

ecms-go-validator

A validator package which offers the parts required for validation as separate parts: messaging templates, validators, validator options, and validator getters.

There are already good validation libraries out there but none that separate out the components of validation into lower level primitives (which are useful for composing your validation components in more precise manners; Example: Validating with locale based content in messaging and allowing multiple messages per input).

Inspired by zend-validator.

Common Use Cases

  • Validating an input (an input could have many validation points (length, notEmpty, specificChars etc.))
  • Validating all inputs in an input map (ex: map[string]Input{}); Same as "Validating form inputs".

Docs

Look at ./ValidatorTypes.go then other sources for now. @todo Add method docs to readme and standalone.

Examples:

Given our default types:

// ./ValidatorTypes.go
package ecms_validator

// For obscuring values in error messages (composed into validators
//  where required (for example in a credit-card validator))
type ValueObscurator func (limit int, str string) string

type MessageFunc func (options ValidatorOptions, x interface{}) string // returns message

type MessageFuncs map[int]MessageFunc // message templates

type ValidatorOptions interface {
	GetMessageFuncs () *MessageFuncs
	GetErrorMessageByKey (key int, value interface{}) string
	GetValueObscurator () ValueObscurator
}

type ValidatorGenerator func (options ValidatorOptions) Validator

type Validator func (x interface{}) (bool, []string)

A trivial validator would look something like:

package somepackage

import (
	. "github.com/extensible-cms/ecms-go-validator"
	. "github.com/extensible-cms/ecms-go-validator/is"
)

type NotNilValidatorOptions struct {
	MessageFuncs *MessageFuncs
}

const (
	DefaultNotNilMsg = "`nil` is not allowed as a value."
	NilNotAllowed = 0x0000ff
)

func NewNotNilValidatorOptions () NotNilValidatorOptions {
	return NotNilValidatorOptions{
		MessageFuncs: &MessageFuncs{
			NilNotAllowed: func(ops ValidatorOptions, x interface{}) string {
				return DefaultNotNilMsg
			},
		},
	}
}

func NotNilValidator (options ValidatorOptions) Validator {
	return func (x interface{}) (bool, []string){
		if x == nil {
			return false, []string{GetErrorMessageByKey(options, NilNotAllowed, x)}
		}
		return true, nil
	}
}

func (n NotNilValidatorOptions) GetErrorMessageByKey (key int, x interface{}) string {
	return GetErrorMessageByKey(n, key, x)
}

func (n NotNilValidatorOptions) GetMessageFuncs () *MessageFuncs {
	return n.MessageFuncs
}

func (n NotNilValidatorOptions) GetValueObscurator () ValueObscurator {
	return DefaultValueObscurator
}

Then usage of created validator:

package somepackage
import "net/http"

type JsonModel struct {
	Request map[string]interface{}
	Errors  map[int]interface{}
	Data    map[string]interface{}
}

func NewJsonModel() JsonModel {
	return JsonModel{
		map[string]interface{}{},
		map[int]interface{}{},
		map[string]interface{}{},
	}
}

// Would preferably be instantiated with action call (and possibly seeded with some locale based error messages
//  for it's given cases)
var notNilValidator = NotNilValidator(NotNilValidatorOptions())

func SomeAction (r *http.Request, w http.ResponseWriter) {
    // Outgoing json view model
    out := NewJsonModel()
    out.Data["success"] = false

    // Or some other model
    incoming := NewJsonModel()
    
    // Ensure there are no errors in http "POST" form data
    if err := r.ParseForm(); err != nil {
        // ...
        return
    }

	// Parse incoming body
	bytesFromBody, err := ioutil.ReadAll(r.Body)
	if err != nil {
		// ...
		return
	}

	// Unmarshal into struct
	if err := json.Unmarshal(bytesFromBody, &incoming); err != nil {
		// ...
		return
	}

    result, messages := notNilValidator(incoming.Data)
    if result != true {
        // ... Write header
        // ... Send back result and messages
        // Hypothetical error-codes package
        out.Errors[errorcodes.INVALID_INPUT_DATA] = errorcodes.messagesMap[errorcodes.INVALID_INPUT_DATA]
        out.Data["messages"] = messages // ui pertinent messages
        out.Data["result"] = result     // ""
        return
    }

    // Else continue with processing
}

@note Input and InputFilter examples coming soon (@todo).

License

BSD-3-Clause

Documentation

Index

Constants

View Source
const (
	DoesNotMatchPattern = iota
	EmptyNotAllowed
	NotAValidType
	NotWithinRange
)
View Source
const (
	DefaultEmptyNotAllowedMsg = "Empty values are not allowed."
)

Variables

View Source
var DefaultInRangeMessageFuncs = MessageFuncs{
	NotAValidType: func(options ValidatorOptions, x interface{}) string {
		return fmt.Sprintf("%v is not a validatable numeric type.", x)
	},
}

Functions

func DefaultValueObscurator

func DefaultValueObscurator(limit int, str string) string

DefaultValueObscurator Returns an obscured string representation of given value. Obscures string using "*" character up to given `limit`.

func GetErrorMessageByKey

func GetErrorMessageByKey(options ValidatorOptions, key int, value interface{}) string

GetErrorMessageByKey is a generic function that gets the message function from a collection of message template functions and calls it using passed in options and value values.

func ObscurateLeft

func ObscurateLeft(numChars int, str string) string

func ObscurateRight

func ObscurateRight(numChars int, str string) string

Types

type FloatValidatorOptions

type FloatValidatorOptions struct {
	MessageFuncs *MessageFuncs
	Min          float64
	Max          float64
	Inclusive    bool
}

func NewFloatRangeValidatorOptions

func NewFloatRangeValidatorOptions() FloatValidatorOptions

func (FloatValidatorOptions) GetErrorMessageByKey

func (n FloatValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string

func (FloatValidatorOptions) GetMessageFuncs

func (n FloatValidatorOptions) GetMessageFuncs() *MessageFuncs

func (FloatValidatorOptions) GetValueObscurator

func (n FloatValidatorOptions) GetValueObscurator() ValueObscurator

type IntValidatorOptions

type IntValidatorOptions struct {
	MessageFuncs *MessageFuncs
	Min          int64
	Max          int64
	Inclusive    bool
}

func NewIntRangeValidatorOptions

func NewIntRangeValidatorOptions() IntValidatorOptions

func (IntValidatorOptions) GetErrorMessageByKey

func (n IntValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string

func (IntValidatorOptions) GetMessageFuncs

func (n IntValidatorOptions) GetMessageFuncs() *MessageFuncs

func (IntValidatorOptions) GetValueObscurator

func (n IntValidatorOptions) GetValueObscurator() ValueObscurator

type LengthValidatorOptions

type LengthValidatorOptions struct {
	MessageFuncs *MessageFuncs
	Min          int64
	Max          int64
	Inclusive    bool
}

func NewLengthValidatorOptions

func NewLengthValidatorOptions() LengthValidatorOptions

func (LengthValidatorOptions) GetErrorMessageByKey

func (n LengthValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string

func (LengthValidatorOptions) GetMessageFuncs

func (n LengthValidatorOptions) GetMessageFuncs() *MessageFuncs

func (LengthValidatorOptions) GetValueObscurator

func (n LengthValidatorOptions) GetValueObscurator() ValueObscurator

type MessageFunc

type MessageFunc func(options ValidatorOptions, x interface{}) string // returns message

type MessageFuncs

type MessageFuncs map[int]MessageFunc // message templates
var DefaultLengthValidatorMessageFuncs MessageFuncs
var (
	DigitValidatorMessageFuncs MessageFuncs
)
var RegexValidatorMessageFuncs *MessageFuncs

type NotEmptyValidatorOptions

type NotEmptyValidatorOptions struct {
	MessageFuncs *MessageFuncs
}

func NewNotEmptyValidatorOptions

func NewNotEmptyValidatorOptions() NotEmptyValidatorOptions

func (NotEmptyValidatorOptions) GetErrorMessageByKey

func (n NotEmptyValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string

func (NotEmptyValidatorOptions) GetMessageFuncs

func (n NotEmptyValidatorOptions) GetMessageFuncs() *MessageFuncs

func (NotEmptyValidatorOptions) GetValueObscurator

func (n NotEmptyValidatorOptions) GetValueObscurator() ValueObscurator

type RegexValidatorOptions

type RegexValidatorOptions struct {
	Pattern      *regexp.Regexp
	MessageFuncs *MessageFuncs
}

func NewRegexValidatorOptions

func NewRegexValidatorOptions() RegexValidatorOptions

func (RegexValidatorOptions) GetErrorMessageByKey

func (n RegexValidatorOptions) GetErrorMessageByKey(key int, x interface{}) string

func (RegexValidatorOptions) GetMessageFuncs

func (n RegexValidatorOptions) GetMessageFuncs() *MessageFuncs

func (RegexValidatorOptions) GetValueObscurator

func (n RegexValidatorOptions) GetValueObscurator() ValueObscurator

type Validator

type Validator func(x interface{}) (bool, []string)

func DigitValidator

func DigitValidator(options RegexValidatorOptions) Validator

DigitValidator - Returns `(true, nil)` for `uint`, `int`, and strings containing only digit characters (numbers). For every other value the returned validator will always return `(false, []string{})` where the second return value is the error messages returned for current run. Note: The `Pattern` property of passed in `RegexValidatorOptions` gets ignored and the internally defined one gets used.

func DigitValidator1

func DigitValidator1() Validator

DigitValidator1 - Ignores options param and just returns a validator which contains default error messages in message templates

func FloatRangeValidator

func FloatRangeValidator(options ValidatorOptions) Validator

func IntRangeValidator

func IntRangeValidator(options ValidatorOptions) Validator

func LengthValidator

func LengthValidator(options LengthValidatorOptions) Validator

func NotEmptyValidator

func NotEmptyValidator(options ValidatorOptions) Validator

func NotEmptyValidator1

func NotEmptyValidator1() Validator

func RegexValidator

func RegexValidator(options RegexValidatorOptions) Validator

type ValidatorGenerator

type ValidatorGenerator func(options ValidatorOptions) Validator

type ValidatorOptions

type ValidatorOptions interface {
	GetMessageFuncs() *MessageFuncs
	GetErrorMessageByKey(key int, value interface{}) string
	GetValueObscurator() ValueObscurator
}

type ValueObscurator

type ValueObscurator func(limit int, str string) string

For obscuring values in error messages (composed into validators

where required (for example in a credit-card validator))

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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