Skip to content

Repository files navigation

gowww check GoDocBuildCoverageGo ReportStatus 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:

    iferrs.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):

iferrs.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:

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

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

varlocales= 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

About

👮‍♂️ Form validation utilities

Topics

Resources

Stars

6 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages