Data validation, cleaning and error collection for golang

Related tags

Forms goforms
Overview

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.

You might also like...
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

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

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

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

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.

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

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

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

: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

💯 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.

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

: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

: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

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

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

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

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

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

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.

    opened by Omie 1
Owner
Michael Nelson
Michael Nelson
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

Matt Holt 790 Sep 12, 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

Alex Browne 132 Jul 18, 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

Go Playgound 556 Sep 21, 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

Vladimir Mihailenco 39 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

Alessandro Frossi 70 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

Christophe Bonello 50 Apr 5, 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

Jerko Steiner 19 Sep 20, 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

Ozzo Framework 2.9k Sep 26, 2022
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

null 0 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.

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

Liang Yaopei 77 Sep 5, 2022