Categorygithub.com/gowww/check
repositorypackage
1.0.0
Repository: https://github.com/gowww/check.git
Documentation: pkg.go.dev

# 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

FunctionUsagePossible errors
AlphaAlphanotAlpha
EmailEmailnotEmail
FileTypeFileType("text/plain")badFileType:text/plain
ImageImagenotImage
IntegerIntegernotInteger
LatitudeLatitudenotLatitude, notNumber
LongitudeLongitudenotLongitude, notNumber
MaxMax(1)max:1, notNumber
MaxFileSizeMaxFileSize(5000000)maxFileSize:5000000
MaxLenMaxLen(1)maxLen:1, notNumber
MinMin(1)min:1, notNumber
MinFileSizeMinFileSize(10)minFileSize:10
MinLenMinLen(1)minLen:1, notNumber
NumberNumbernotNumber
PhonePhonenotPhone
RangeRange(1, 5)max:5, min:1, notNumber
RangeLenRangeLen(1, 5)maxLen:5, minLen:1
RequiredRequiredrequired
SameSame("key1", "key2")notSame:key1,key2
UniqueUnique(db, "users", "email", "?")notUnique
URLURLnotURL