Package check provides request form checking.
-
Get package:
go get -u github.com/gowww/check
-
Import it in your code:
import "github.com/gowww/check"
-
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.
-
Check data:
-
From a values map, with Checker.CheckValues:
errs := userChecker.CheckValues(map[string][]string{ "name": {"foobar"}, "phone": {"0012345678901"}, })
-
From an http.Request, with Checker.CheckRequest:
errs := userChecker.CheckRequest(r)
-
-
Handle errors:
if errs.NotEmpty() { fmt.Println(errs) }
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 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.
Function | Usage | Possible errors |
---|---|---|
Alpha | Alpha |
notAlpha |
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 |