1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-19 04:30:53 +00:00
Beego/validation
astaxie a002f78443 Merge pull request #1097 from pylemon/develop
form required validate for bool field bugfix
2015-03-27 23:04:07 +08:00
..
README.md Fixed docs: HasErrors is a method not a variable 2014-07-29 15:05:04 +02:00
util_test.go update the documents & comments 2014-08-18 16:41:43 +08:00
util.go gofmt -s & go_vet 2015-03-19 22:29:01 -07:00
validation_test.go add tests to ensure bool value require test always return true. 2015-03-27 13:43:20 +08:00
validation.go Set ErrorsMap to nil in Validation.Clear function 2015-03-26 20:23:00 +01:00
validators.go bugfix: if a form field type is bool, valid Required should always return true instead of return its value. 2015-03-27 13:30:59 +08:00

validation

validation is a form validation for a data validation and error collecting using Go.

Installation and tests

Install:

go get github.com/astaxie/beego/validation

Test:

go test github.com/astaxie/beego/validation

Example

Direct Use:

import (
	"github.com/astaxie/beego/validation"
	"log"
)

type User struct {
	Name string
	Age int
}

func main() {
	u := User{"man", 40}
	valid := validation.Validation{}
	valid.Required(u.Name, "name")
	valid.MaxSize(u.Name, 15, "nameMax")
	valid.Range(u.Age, 0, 140, "age")
	if valid.HasErrors() {
		// validation does not pass
		// print invalid message
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
		}
	}
	// or use like this
	if v := valid.Max(u.Age, 140); !v.Ok {
		log.Println(v.Error.Key, v.Error.Message)
	}
}

Struct Tag Use:

import (
	"github.com/astaxie/beego/validation"
)

// validation function follow with "valid" tag
// functions divide with ";"
// parameters in parentheses "()" and divide with ","
// Match function's pattern string must in "//"
type user struct {
	Id   int
	Name string `valid:"Required;Match(/^(test)?\\w*@;com$/)"`
	Age  int    `valid:"Required;Range(1, 140)"`
}

func main() {
	valid := Validation{}
	u := user{Name: "test", Age: 40}
	b, err := valid.Valid(u)
	if err != nil {
		// handle error
	}
	if !b {
		// validation does not pass
		// blabla...
	}
}

Struct Tag Functions:

Required
Min(min int)
Max(max int)
Range(min, max int)
MinSize(min int)
MaxSize(max int)
Length(length int)
Alpha
Numeric
AlphaNumeric
Match(pattern string)
AlphaDash
Email
IP
Base64
Mobile
Tel
Phone
ZipCode

LICENSE

BSD License http://creativecommons.org/licenses/BSD/