validator

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2019 License: MIT Imports: 6 Imported by: 0

README

Validator

A sane wrapper around the standard validator library. Supports errors for custom validators, and a few more useful validators.

Installation

go get github.com/eddieowens/validator

Usage

package main

import (
    "errors"
    "fmt"
    "github.com/eddieowens/validator"
    ogvalid "gopkg.in/go-playground/validator.v9"
)

func main() {
    type myStruct struct {
        Required                    string `validate:"required"`
        AnswerToTheUltimateQuestion int    `validate:"answer_to_the_ultimate_question"`
    }
    
    v := validator.NewValidator()
    
    v.SetFieldTagValidator("answer_to_the_ultimate_question", func(level ogvalid.FieldLevel) error {
        i := level.Field().Int()
        if i == 42 {
            return nil
        }
        return fmt.Errorf("%d is not the ultimate answer to life, the universe, and everything!", i)
    })
    
    s := myStruct{
        Required:                    "required",
        AnswerToTheUltimateQuestion: 42,
    }
    
    if err := v.Struct(s); err != nil {
        panic(err)
    }
    
    // Success!
}

A few methods were added to the original validator package to allow you to better manage errors.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ErrorFactory

type ErrorFactory func(e validator.FieldError) error

type FieldValidation

type FieldValidation func(level validator.FieldLevel) error

type TagErrorMap

type TagErrorMap map[string]ErrorFactory

type ValidationErrorMutator

type ValidationErrorMutator func(*ValidationErrors)

type ValidationErrors

type ValidationErrors []error

func (ValidationErrors) Error

func (v ValidationErrors) Error() string

type Validator

type Validator struct {
	*validator.Validate
	// contains filtered or unexported fields
}

func NewValidator

func NewValidator() *Validator

func (*Validator) DefaultErrorMessage

func (v *Validator) DefaultErrorMessage(factory ErrorFactory)

Set a default error message template for all validator errors.

func (*Validator) OverrideErrorMessage

func (v *Validator) OverrideErrorMessage(tag string, factory ErrorFactory)

Override the error message factory for a particular validation.

func (*Validator) SetFieldTagValidator

func (v *Validator) SetFieldTagValidator(tag string, validation FieldValidation)

Create a custom field tag validator that returns an error message.

func (*Validator) Struct

func (v *Validator) Struct(s interface{}) error

Jump to

Keyboard shortcuts

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