check

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 14, 2019 License: MIT Imports: 15 Imported by: 1

README

gowww check GoDoc Build Coverage Go Report Status Testing

Package check provides request form checking.

Installing

  1. Get package:

    go get -u github.com/gowww/check
    
  2. Import it in your code:

    import "github.com/gowww/check"
    

Usage

  1. Make a Checker with rules for keys:

    userChecker := check.Checker{
    	"email":   {check.Required, check.Email, check.Unique(db, "users", "email", "?")},
    	"phone":   {check.Phone},
    	"picture": {check.MaxFileSize(5000000), check.Image},
    }
    

    The rules order is significant so for example, it's smarter to check the format of a value before its uniqueness, avoiding some useless database requests.

  2. Check data:

  3. Handle errors:

    if errs.NotEmpty() {
    	fmt.Println(errs)
    }
    
JSON

Use Errors.JSON to get errors in a map under errors key, ready to be JSON formatted (as an HTTP API response, for example):

if errs.NotEmpty() {
	errsjs, _ := json.Marshal(errs.JSON())
	w.Write(errsjs)
}
Internationalization

Internationalization is handled by gowww/i18n and there are built-in translations for all errors.

Use Errors.T with an i18n.Translator (usually stored in the request context) to get translated errors:

if errs.NotEmpty() {
	transErrs := errs.T(i18n.RequestTranslator(r))
	fmt.Println(transErrs)
}

You can provide custom translations for each error type under keys like "error + RuleName":

var locales = i18n.Locales{
	language.English: {
		"hello": "Hello!",

		"errorMaxFileSize": "File too big (%v max.)",
		"errorRequired":    "Required field",
	},
}

If the i18n.Translator is nil or a custom translation is not found, the built-in translation of error is used.

Rules
Function Usage Possible errors
Alpha Alpha notAlpha
Email Email notEmail
FileType FileType("text/plain") badFileType:text/plain
Image Image notImage
Integer Integer notInteger
Latitude Latitude notLatitude, notNumber
Longitude Longitude notLongitude, notNumber
Max Max(1) max:1, notNumber
MaxFileSize MaxFileSize(5000000) maxFileSize:5000000
MaxLen MaxLen(1) maxLen:1, notNumber
Min Min(1) min:1, notNumber
MinFileSize MinFileSize(10) minFileSize:10
MinLen MinLen(1) minLen:1, notNumber
Number Number notNumber
Phone Phone notPhone
Range Range(1, 5) max:5, min:1, notNumber
RangeLen RangeLen(1, 5) maxLen:5, minLen:1
Required Required required
Same Same("key1", "key2") notSame:key1,key2
Unique Unique(db, "users", "email", "?") notUnique
URL URL notURL

Documentation

Overview

Package check provides request form checking.

Example
package main

import (
	"fmt"

	"github.com/gowww/check"
)

func main() {
	checker := check.Checker{
		"email":   {check.Required, check.Email},
		"phone":   {check.Phone},
		"picture": {check.MaxFileSize(5000000), check.Image},
	}

	errs := checker.CheckValues(map[string][]string{
		"name":  {"foobar"},
		"phone": {"0012345678901"},
	})

	if errs.NotEmpty() {
		fmt.Println(errs)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrBadFileType = &ErrorID{ID: "badFileType", Locales: map[language.Tag]string{
		language.English: "Only these file types are accepted: %v.",
		language.French:  "Seul ces types de fichier sont acceptés: %v.",
	}}
	ErrIllogical = &ErrorID{ID: "illogical", Locales: map[language.Tag]string{
		language.English: "This value is illogical.",
		language.French:  "Cette valeur est illogique.",
	}}
	ErrInvalid = &ErrorID{ID: "invalid", Locales: map[language.Tag]string{
		language.English: "This value is invalid.",
		language.French:  "Cette valeur est invalide.",
	}}
	ErrMax = &ErrorID{ID: "max", Locales: map[language.Tag]string{
		language.English: "The maximal value is %v.",
		language.French:  "La valeur maximale est de %v",
	}}
	ErrMaxFileSize = &ErrorID{ID: "maxFileSize", Locales: map[language.Tag]string{
		language.English: "File size is over %v.",
		language.French:  "La taille du fichier dépasse %v.",
	}}
	ErrMaxLen = &ErrorID{ID: "maxLen", Locales: map[language.Tag]string{
		language.English: "The value exceeds %v characters.",
		language.French:  "La valeur dépasse %v caractères.",
	}}
	ErrMin = &ErrorID{ID: "min", Locales: map[language.Tag]string{
		language.English: "The minimal value is %v.",
		language.French:  "La valeur minimale est de %v",
	}}
	ErrMinFileSize = &ErrorID{ID: "minFileSize", Locales: map[language.Tag]string{
		language.English: "File size must be at least %v.",
		language.French:  "La taille du fichier doit être d'au moins %v.",
	}}
	ErrMinLen = &ErrorID{ID: "minLen", Locales: map[language.Tag]string{
		language.English: "The value must have more than %v characters.",
		language.French:  "La veleur doit comporter au moins %v caractères.",
	}}
	ErrNotAlpha = &ErrorID{ID: "notAlpha", Locales: map[language.Tag]string{
		language.English: "It's not a letters-only string.",
		language.French:  "Ce n'est pas une suite de lettres (uniquement).",
	}}
	ErrNotAlphanumeric = &ErrorID{ID: "notAlphanumeric", Locales: map[language.Tag]string{
		language.English: "It's not an alphanumeric-only string.",
		language.French:  "Ce n'est pas une suite alphanumérique (uniquement).",
	}}
	ErrNotEmail = &ErrorID{ID: "notEmail", Locales: map[language.Tag]string{
		language.English: "It's not an email.",
		language.French:  "Ce n'est pas un e-mail.",
	}}
	ErrNotFloat = &ErrorID{ID: "notFloat", Locales: map[language.Tag]string{
		language.English: "It's not a floating point number.",
		language.French:  "Ce n'est pas un nombre à virgule.",
	}}
	ErrNotImage = &ErrorID{ID: "notImage", Locales: map[language.Tag]string{
		language.English: "It's not an image.",
		language.French:  "Ce n'est pas une image.",
	}}
	ErrNotInteger = &ErrorID{ID: "notInteger", Locales: map[language.Tag]string{
		language.English: "It's not a integer number.",
		language.French:  "Ce n'est pas un nombre entier.",
	}}
	ErrNotLatitude = &ErrorID{ID: "notLatitude", Locales: map[language.Tag]string{
		language.English: "It's not a latitude.",
		language.French:  "Ce n'est pas une latitude.",
	}}
	ErrNotLongitude = &ErrorID{ID: "notLongitude", Locales: map[language.Tag]string{
		language.English: "It's not a longitude.",
		language.French:  "Ce n'est pas une longitude.",
	}}
	ErrNotNumber = &ErrorID{ID: "notNumber", Locales: map[language.Tag]string{
		language.English: "It's not a number.",
		language.French:  "Ce n'est pas un nombre.",
	}}
	ErrNotPhone = &ErrorID{ID: "notPhone", Locales: map[language.Tag]string{
		language.English: "It's not a phone number.",
		language.French:  "Ce n'est pas un numéro de téléphone.",
	}}
	ErrNotSame = &ErrorID{ID: "notSame", Locales: map[language.Tag]string{
		language.English: "The value must equals these fields: %v.",
		language.French:  "La valeur doit être identique aux champs suivants: %v.",
	}}
	ErrNotURL = &ErrorID{ID: "notURL", Locales: map[language.Tag]string{
		language.English: "It's not a web address.",
		language.French:  "Ce n'est pas une adresse web.",
	}}
	ErrNotUnique = &ErrorID{ID: "notUnique", Locales: map[language.Tag]string{
		language.English: "This value already exists.",
		language.French:  "Cette valeur existe déjà.",
	}}
	ErrRequired = &ErrorID{ID: "required", Locales: map[language.Tag]string{
		language.English: "A value is required.",
		language.French:  "Une valeur est requise.",
	}}
	ErrWrongPassword = &ErrorID{ID: "password", Locales: map[language.Tag]string{
		language.English: "The password is wrong.",
		language.French:  "Le mot de passe est incorrect.",
	}}
)

Error identifiers. The first locale in Locales map is used when no one matched.

Functions

func Alpha

func Alpha(errs Errors, form *multipart.Form, key string)

Alpha rule checks that value contains alpha characters only.

func Alphanumeric

func Alphanumeric(errs Errors, form *multipart.Form, key string)

Alphanumeric rule checks that value contains alphaumeric characters only.

func Email

func Email(errs Errors, form *multipart.Form, key string)

Email rule checks that value represents an email.

func Image

func Image(errs Errors, form *multipart.Form, key string)

Image rule checks that file is GIF, JPEG or PNG.

func Integer

func Integer(errs Errors, form *multipart.Form, key string)

Integer rule checks that value represents an integer.

func Latitude

func Latitude(errs Errors, form *multipart.Form, key string)

Latitude rule checks that value represents a latitude.

func Longitude

func Longitude(errs Errors, form *multipart.Form, key string)

Longitude rule checks that value represents a longitude.

func Number

func Number(errs Errors, form *multipart.Form, key string)

Number rule checks that value represents a number.

func Phone

func Phone(errs Errors, form *multipart.Form, key string)

Phone rule checks that value represents a phone number.

func Required

func Required(errs Errors, form *multipart.Form, key string)

Required rule checks that value or file exists and is not empty. A value is not trimmed so a single space can pass the check.

func URL

func URL(errs Errors, form *multipart.Form, key string)

URL rule checks that value represents an URL.

Types

type Checker

type Checker map[string][]Rule

A Checker contains keys with their checking rules.

func (Checker) Check

func (c Checker) Check(form *multipart.Form) Errors

Check makes the check for a multipart.Form (values and files) and returns errors.

Result is guaranteed to be non-nil.

func (Checker) CheckFiles

func (c Checker) CheckFiles(files map[string][]*multipart.FileHeader) Errors

CheckFiles makes the check for a files map (key to multiple files) and returns errors.

Result is guaranteed to be non-nil.

func (Checker) CheckRequest

func (c Checker) CheckRequest(r *http.Request) Errors

CheckRequest makes the check for an HTTP request and returns errors.

Request data can have multiple values with the same key (or field). In this case, all values are checked and if one fails, the error is set for the whole key.

Result is guaranteed to be non-nil.

func (Checker) CheckValues

func (c Checker) CheckValues(values map[string][]string) Errors

CheckValues makes the check for a values map (key to multiple values) and returns errors.

Result is guaranteed to be non-nil.

type Error

type Error struct {
	Error *ErrorID
	Args  []interface{}
}

An Error is a checking error from a rule, with rule's variables.

func (*Error) String

func (e *Error) String() string

func (*Error) T

func (e *Error) T(t *i18n.Translator) string

T returns an Error translation from an i18n.Translator (from key "error" + title case error ID, like "errorNotImage"). If custom translation is not defined, the default ErrorID translation is used.

func (*Error) TDefault

func (e *Error) TDefault(l language.Tag) string

TDefault returns the default translation of Error. If Error has no translations, the raw string representation.

type ErrorID

type ErrorID struct {
	ID      string
	Locales map[language.Tag]string
}

An ErrorID defines a standard and translatable error to be used during a check.

type Errors

type Errors map[string][]*Error

Errors is a map of keys and their errors.

func (Errors) Add

func (e Errors) Add(key string, err *Error)

Add appends a failed validation Error to key.

func (Errors) Empty

func (e Errors) Empty() bool

Empty tells if the errors map contains no keys.

func (Errors) First

func (e Errors) First(key string) *Error

First returns the first error for key. If the key doesn't exist, nil.

func (Errors) Has

func (e Errors) Has(key string) bool

Has tells if the errors map contains a key.

func (Errors) JSON

func (e Errors) JSON() interface{}

JSON returns the errors map under the "errors" key, ready to be encoded.

func (Errors) Merge

func (e Errors) Merge(e2 Errors)

Merge merges two Errors maps.

func (Errors) NotEmpty

func (e Errors) NotEmpty() bool

NotEmpty tells if the errors map contains keys.

func (Errors) String

func (e Errors) String() string

func (Errors) StringMap

func (e Errors) StringMap() map[string][]string

StringMap returns the errors as a readable string map.

func (Errors) T

T returns a tranlated Errors map. If t is nil, built-in translations are used.

type Rule

type Rule func(errs Errors, form *multipart.Form, key string)

A Rule is a checking function to be used inside a Checker. It receives the errors map to add encountered errors, the whole form for relative checks, and the specific key to check.

func FileType

func FileType(types ...string) Rule

FileType rule checks that file is one of given MIME types.

func Max

func Max(max float64) Rule

Max rule checks that value is below or equals max.

func MaxFileSize

func MaxFileSize(max int64) Rule

MaxFileSize rule checks if file has max or less bytes.

func MaxLen

func MaxLen(max int) Rule

MaxLen rule checks that value length is below or equals max.

func Min

func Min(min float64) Rule

Min rule checks that value is over or equals min.

func MinFileSize

func MinFileSize(min int64) Rule

MinFileSize rule checks if file has min or more bytes.

func MinLen

func MinLen(min int) Rule

MinLen rule checks that value length is over or equals min.

func Range

func Range(min, max float64) Rule

Range rule checks that value represents a number inside a range.

func RangeFileSize

func RangeFileSize(min, max int64) Rule

RangeFileSize rule checks if file length is inside a range.

func RangeLen

func RangeLen(min, max int) Rule

RangeLen rule checks that value length is inside a range.

func Same

func Same(keys ...string) Rule

Same rule checks that value deeply equals another key value.

func Unique

func Unique(db *sql.DB, table, column, placeholder string) Rule

Unique rule checks that value is unique in database. The placeholder ("?", "$1" or other) must be provided as it depends on the SQL driver.

type TranslatedErrors

type TranslatedErrors map[string][]string

TranslatedErrors is a map of keys and their translated errors.

func (TranslatedErrors) First

func (e TranslatedErrors) First(key string) string

First returns the first translated error for key. If the key doesn't exist, an empty string.

func (TranslatedErrors) Has

func (e TranslatedErrors) Has(key string) bool

Has tells if the translated errors map contains a key.

Jump to

Keyboard shortcuts

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