Skip to content
master
Go to file
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

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

About

๐Ÿ‘ฎโ€โ™‚๏ธ Form validation utilities

Topics

Resources

License

Packages

No packages published

Languages

You canโ€™t perform that action at this time.