GoForms - form data validation, cleaning and error reporting
The goforms library is a proof-of-concept for a data validation, cleaning and
error collecting using Go, in a similar style to Django's django.forms
library. It enables thin handlers like this:
func my_post_handler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Invalid request form data", 400)
return
}
myForm := MyCustomForm()
myForm.Data = r.Form
if myForm.IsValid() {
} else {
}
For another form-data processing library, see Gorilla/schema, which fills structs with form data using struct tags.
Installation and tests
To install goforms into your current Go workspace:
$ go get github.com/absoludity/goforms/forms
You can then run the tests with
$ go test github.com/absoludity/goforms/fields github.com/absoludity/goforms/forms
Example
Define your form
formFields := FormFields{
"name": fields.NewCharField(fields.Defaults{
"Required": true,
}),
"age": fields.NewIntegerField(fields.Defaults{
"Required": false,
}),
"about": fields.NewCharField(fields.Defaults{
"Max": 10,
}),
}
personForm := Form{Fields: formFields}
Use the form in your handler
Using the http.Request objects Form (r.Form):
personForm.Data = r.Form
if personForm.IsValid() {
doStuffWithCleanedData()
} else {
doStuffWithErrors()
}
Notes
TODO
- Remove Form.Data, and instead provide data to Form.IsValid()
- Perhaps make Form.CleanedData and Form.Errors private, providing getters.
- Add defaults to fields so that a value is always included.
- Enable custom error messages.
- Update field tests to use nicer in/out for test tables like form_tests.
License
Copyright 2012 The GoForms Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.