GithubHelp home page GithubHelp logo

validation's Introduction

###martini-validate

The idea behind this package is to give some nice default validation handlers for input handlers.

The package was developed with respect to the Martini Binding repo, but can actually be used very generically by implementing the Errors interface.

###Usage

func (contactRequest ContactRequest) Validate(errors binding.Errors, req *http.Request) binding.Errors {

    v := NewValidation(&errors, contactRequest)

	// //run some validators
	v.Validate(&contactRequest.FullName).Key("fullname").MaxLength(20)
	v.Validate(&contactRequest.Email).Default("Custom Email Validation Message").Classify("email-class").Email()
	v.Validate(&contactRequest.Comments).TrimSpace().MinLength(10)

	return *v.Errors.(*binding.Errors)
}

type ContactRequest struct {
	FullName string `form:"full_name" binding:"required"`
	Email    string `form:"email" binding:"required"`
	Subject  string `form:"subject"`
	Comments string `form:"comments"`
}

This will generate something like:

[
    {
        "fieldNames": [
            "fullname"
        ],
        "message": "Maximum Length is 20"
    },
    {
        "fieldNames": [
            "email"
        ],
        "classification": "email-class",
        "message": "Custom Email Validation Message"
    },
    {
        "fieldNames": [
            "comments"
        ],
        "message": "Minimum Length is 10"
    }
]

###Configuration

By default, the validator will grab the form key out of the struct tag to use as the output key. This is nice because if you're using the form tag already you don't have to write out any additional keys, which keeps things DRY.

To change what struct tag will be used to map the errors, use Validation.KeyTag(string).

Keys can also be specified on per validation basis by chaining .Key(string). Note that you must use this before you call the validator, as errors get mapped immeditaly after you call a validator.

Also, make sure to pass the struct fields in as pointers if you want the validator to be able to make changes to the underlying values. For example, TrimSpace() cant actually trim the space unless it recieves a pointer.

###API Pre-Build Validators:

  • MaxLength(maxLength int) / MinLength(minLength int) - works on strings, arrays, and maps
  • Range(min, max) - short hand for calling MinLength(int) & MaxLength(int)
  • *Matches(regex regexp.Regexp) - returns true if it meets the regex
  • *NoMatch(regex regexp.Regex)
  • Email() - uses matches pattern
  • CreditCard() matches Visa, MasterCard, American Express, Diners Club, Discover, and JCB cards
  • URL() matches most url schemes

As well as some utilities, like

  • TrimSpace() - trims whitespace
  • Message(message string) - overrides default error message
  • Classify(classification string) - sets classification
  • Key(str string) - set the key to map out to

More that I want to add when I have time:

  • EqualTo (other form field)
  • Use matches pattern to do other pattern like examples

###Contributions welcome! Todo's:

  • Write some validators on the http.Request. For example, HasHeader(), etc
  • Improve the syntax to handle multi-field errors
  • Add some of the validators listed as want-to-haves above
  • Improve Test Coverage

Ideas inspired from the jQuery validation plugin as well as the way .NET MVC handles model validation.

validation's People

Contributors

jamieomatthews avatar patricksuo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

validation's Issues

Outdated readme.

This code:

func (ur UserRegistration) Validation(errors binding.Errors, req *http.Request) binding.Errors {
    v := validation.NewValidation(errors, ur)

    v.Validate(&ur.Name).Key("fullname").MaxLength(20)
    v.Validate(&ur.Email).Default("Custom Email Validation Message").Classify("email-class").Email()
    v.Validate(&ur.PlainPassword).TrimSpace().MinLength(6)

    return *v.Errors.(*binding.Errors)
}

produce some errors:

cannot use errors (type binding.Errors) as type validation.Errors in function argument:
    binding.Errors does not implement validation.Errors (Add method has pointer receiver)
v.Validate(&ur.Email).Default undefined (type *validation.Set has no field or method Default)

get incorrect key when two fields have the same value

Validation.getKeyForField compare v.Obj 's filed value to passedField value to figure out the key. If two fields have the same value, it picks the first matched field and may return an incorrect key.

package main

import (
        "fmt"

        //"github.com/jamieomatthews/validation"
        "github.com/sillyousu/validation"
)

type User struct {
        Name string `form:"username"`
        NickName string `form:"nickname"`
}

func main() {
        user := &User{Name: "su21", NickName: "su21"}
       //I want to get an empty `validation.Errors{}` 
        errors := validation.NewErrors()
        v := validation.New(errors, user)
        v.Validate(user.NickName).MinLength(5)

        fmt.Println("============")
        for i := 0; i < v.Errors.Len(); i++ {
                err := v.Errors.At(i)
                fmt.Printf("\nerr: %#v\n", err)
        }
}

Result

TypeObj: *main.User
Field: su21  passedField: su21
Is Equal!!
Got Key?  username
Min Length: ' su21 '
============

err: &validation.error{fields:[]string{"username"}, classification:"", message:"Minimum Length is 5"}

I think v.Validate("FieldName") is more reasonable.

binding.Errors does not implement validation.Errors

I can't seem to use this with the given example and binding:

cannot use errors (type binding.Errors) as type validation.Errors in function argument:
    binding.Errors does not implement validation.Errors (missing Add method)
impossible type assertion:
    *binding.Errors does not implement validation.Errors (missing Add method)

It's the latest binding (from today)

Also what is the interface part in NewValidation?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.