Data validation, cleaning and error collection for golang

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) {
    // Fill r.Form
    if err := r.ParseForm(); err != nil {
        http.Error(w, "Invalid request form data", 400)
        return
    }    
    myForm := MyCustomForm()
    myForm.Data = r.Form

    if myForm.IsValid() {
        // Do something with myForm.CleanedData, which is the request's form
        // data after being cleaned to the correct types etc.
    } else {
        // Re-render a template, passing in myForm.Errors which is a map
        // of errors for each field on the form.
    }

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()
		// personForm.CleanedData contains cleaned data
		// (ie. an int for age in this case):
		// {"name": "Michael Nelson", "age": 37}
		// so that for required fields you can safely do:
		// var age int = personForm.CleanedData["age"].(int)
	} else {
		doStuffWithErrors()
		// If personForm.Data = urls.Values{"age": {"Not a number"}},
		// then personForm.Errors would be {
		//	 "name": "This field is required.",
		//	 "age":  "The value ust be a valid integer."
		// }
	}

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.

Similar Resources

Music recognition bot for Reddit powered by audd.io. Note that the code currently needs some cleaning up and doesn't follow the best practices.

Music recognition bot for Reddit u/auddbot identifies music on Reddit. When someone mentions it or writes a question like "what's the song", it sends

Dec 30, 2022

Simple and easy to use command line application written in Go for cleaning unnecessary XCode files.

xcclear Say hello to a few extra gigabytes of space on your Mac with xcclear, a simple and easy to use command line application written in Go for clea

Dec 16, 2022

Wraps the normal error and provides an error that is easy to use with net/http.

Go HTTP Error Wraps the normal error and provides an error that is easy to use with net/http. Install go get -u github.com/cateiru/go-http-error Usage

Dec 20, 2021

Go error library with error portability over the network

cockroachdb/errors: Go errors with network portability This library aims to be used as a drop-in replacement to github.com/pkg/errors and Go's standar

Dec 29, 2022

Govalid is a data validation library that can validate most data types supported by golang

Govalid is a data validation library that can validate most data types supported by golang. Custom validators can be used where the supplied ones are not enough.

Apr 22, 2022

⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。

Validate The package is a generic Go data validate and filter tool library. Support quick validate Map, Struct, Request(Form, JSON, url.Values, Upload

Dec 28, 2022

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Validate Golang request data with simple rules. Highly inspired by Laravel's request validation.

Validate golang request data with simple rules. Highly inspired by Laravel's request validation. Installation Install the package using $ go get githu

Dec 29, 2022

Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

Nov 9, 2022

Fadvisor(FinOps Advisor) is a collection of exporters which collect cloud resource pricing and billing data guided by FinOps, insight cost allocation for containers and kubernetes resource

Fadvisor(FinOps Advisor) is a collection of exporters which collect cloud resource pricing and billing data guided by FinOps, insight cost allocation for containers and kubernetes resource

[TOC] Fadvisor: FinOps Advisor fadvisor(finops advisor) is used to solve the FinOps Observalibility, it can be integrated with Crane to help users to

Jan 3, 2023

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Package validator Package validator implements value validations for structs and individual fields based on tags. It has the following unique features

Jan 1, 2023

💯 Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Package validator implements value validations for structs and individual fields based on tags.

Nov 9, 2022

Fast and light-weight API proxy firewall for request and response validation by OpenAPI specs.

Fast and light-weight API proxy firewall for request and response validation by OpenAPI specs.

Open Source API Firewall API Firewall is a high-performance proxy with API request and response validation based on OpenAPI/Swagger schema. It is desi

Jan 8, 2023

DEPRECATED: Data collection and processing made easy.

This project is deprecated. Please see this email for more details. Heka Data Acquisition and Processing Made Easy Heka is a tool for collecting and c

Nov 30, 2022

A flexible process data collection, metrics, monitoring, instrumentation, and tracing client library for Go

A flexible process data collection, metrics, monitoring, instrumentation, and tracing client library for Go

Package monkit is a flexible code instrumenting and data collection library. See documentation at https://godoc.org/gopkg.in/spacemonkeygo/monkit.v3 S

Dec 14, 2022

Gosfdc module - a collection of packages containing the data structures from the various Salesforce APIs and Tools

Gosfdc module - a collection of packages containing the data structures from the various Salesforce APIs and Tools

Jan 21, 2022

:key: Idiotproof golang password validation library inspired by Python's passlib

passlib for go Python's passlib is quite an amazing library. I'm not sure there's a password library in existence with more thought put into it, or wi

Dec 30, 2022

:key: Idiotproof golang password validation library inspired by Python's passlib

passlib for go 100% modules-free. Python's passlib is quite an amazing library. I'm not sure there's a password library in existence with more thought

Dec 19, 2022

Quick and Easy server testing/validation

Quick and Easy server testing/validation

Goss - Quick and Easy server validation Goss in 45 seconds Note: For an even faster way of doing this, see: autoadd Note: For testing docker container

Oct 7, 2022

Swagger builder and input validation for Go servers

Swagger builder and input validation for Go servers

crud A Swagger/OpenAPI builder and validation library for building HTTP/REST APIs. Heavily inspired by hapi and the hapi-swagger projects. No addition

Jan 5, 2023
Comments
  • Empty value validation fix

    Empty value validation fix

    Fixed the way empty values were handled.

    Even if there is an empty value, it would return values with length 1, reason for this behavior lies in the url.ParseQuery() implementation.

    The tests were passing because a handcrafted structure of type url.Values was being used. In real scenarios that is not the case. The form data that we use, request.Form is a result of ParseQuery()

    I have fixed the tests to mimic this behavior. If you cherrypick to this commit and run the tests, you'd see the difference.

    Fix is easy enough. Simply check for empty values again in case 1: and set exists=false if that be true.

    Tested with 1.3.1 linux/amd64

    Thanks for writing this. I have quite strong django background and wanted to have something similar for validation.

Related tags
Reflectionless data binding for Go's net/http (not actively maintained)
Reflectionless data binding for Go's net/http (not actively maintained)

binding Reflectionless data binding for Go's net/http Features HTTP request data binding Data validation (custom and built-in) Error handling Benefits

Nov 18, 2022
A lightweight go library for parsing form data or json from an http.Request.

Forms Forms is a lightweight, but incredibly useful go library for parsing form data from an http.Request. It supports multipart forms, url-encoded fo

Dec 16, 2022
:steam_locomotive: Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.

Package form Package form Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. It has the following features: Supports map of

Dec 26, 2022
HTML forms for Golang

HTML forms for Golang Installation: go get github.com/vmihailenco/gforms Example Example: package blog import ( "net/http" "github.com/vmih

Apr 3, 2020
Golang Forms made easy.

Go-FORM-it Description go-form-it makes form creation and handling easy. It allows the creation of form without having to write HTML code or bother to

Aug 20, 2022
CSRF prevention for the Golang Revel framework.

revel-csrf revel-csrf implements Cross-Site Request Forgery (CSRF) attacks prevention for the Revel framework. Code is based on the nosurf package imp

Dec 7, 2022
Go library for parsing and submitting HTML forms

gosubmit Description Docs are available here: https://godoc.org/github.com/jeremija/gosubmit Helps filling out plain html forms during testing. Will a

Nov 14, 2022
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.

ozzo-validation Description ozzo-validation is a Go package that provides configurable and extensible data validation capabilities. It has the followi

Jan 7, 2023
An info-grabber that delivers to a Discord webhook. Doesn't remove data, ignorant executors will think it's a file cleaning application.
An info-grabber that delivers to a Discord webhook. Doesn't remove data, ignorant executors will think it's a file cleaning application.

Disclaimer This was made for "educational" purposes ONLY. Files You can compile main.go after editing its code (make sure to also install the go.mod f

Dec 7, 2021
Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.
Golang parameter validation, which can replace go-playground/validator, includes ncluding Cross Field, Map, Slice and Array diving, provides readable,flexible, configurable validation.

Checker 中文版本 Checker is a parameter validation package, can be use in struct/non-struct validation, including cross field validation in struct, elemen

Dec 16, 2022