Skip to content
This repository has been archived by the owner on Jul 28, 2020. It is now read-only.

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
zhevron committed Jul 6, 2015
0 parents commit c9ec2e3
Show file tree
Hide file tree
Showing 12 changed files with 617 additions and 0 deletions.
79 changes: 79 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Created by http://www.gitignore.io

### Go ###
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so

# Folders
_obj
_test

# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out

*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*

_testmain.go

*.exe
*.test
*.prof


### Linux ###
*~

# KDE directory preferences
.directory


### OSX ###
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear on external disk
.Spotlight-V100
.Trashes

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk


### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Thomas Lokshall

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
go-validate - Object validation library
=======================================

[![wercker status](https://app.wercker.com/status/75af4a3e778a36be820d46a947868b89/s "wercker status")](https://app.wercker.com/project/bykey/75af4a3e778a36be820d46a947868b89)
[![Coverage Status](https://coveralls.io/repos/zhevron/go-validate/badge.svg?branch=HEAD)](https://coveralls.io/r/zhevron/go-validate)
[![GoDoc](https://godoc.org/gopkg.in/zhevron/go-validate.v0/validate?status.svg)](https://godoc.org/gopkg.in/zhevron/go-validate.v0/validate)

**go-validate** is an object validation library for [Go](https://golang.org/).

For package documentation, refer to the GoDoc badge above.

## Installation

```
go get gopkg.in/zhevron/go-validate.v0/validate
```

## Usage

```go
package main

import (
"fmt"

"gopkg.in/zhevron/go-validate.v0/validate"
)

type MyObject struct {
String string `minLen:"10" maxLen:"50"`
Int int `min:"5"`
Error error `nil:"false"`
}

func main() {
var obj MyObject

if ok, errs := validate.Validate(obj); !ok {
fmt.Println("The following validation errors occured:")

for _, err := range errs {
fmt.Printf(" %s\n", err.Error())
}
}
}
```

## License

**go-validate** is licensed under the [MIT license](http://opensource.org/licenses/MIT).
78 changes: 78 additions & 0 deletions validate/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Package validate provides object field validation through reflection.
package validate

import (
"fmt"
"reflect"

"github.com/zhevron/go-validate/validate/validators"
)

// validator defines the function signature for a validator.
type validator func(string, string, reflect.Value) error

// Maps each validator function to its tag name.
var validatorFuncs = map[string]validator{
"nil": validators.Nil,
"min": validators.Min,
"max": validators.Max,
"minLen": validators.MinLen,
"maxLen": validators.MaxLen,
}

// Validate attempts to validate a struct object, looping each field in the
// object and checking for validation tags.
func Validate(o interface{}) (bool, []error) {
var err []error
v := reflect.ValueOf(o)

if v.Kind() == reflect.Ptr {
v = v.Elem()
}

if v.Kind() != reflect.Struct {
fmt.Println(v.Kind().String())
err = append(err, fmt.Errorf("Type %#q is not a struct", v.Type().Name()))
return false, err
}

for i := 0; i < v.NumField(); i++ {
f := v.Type().Field(i)
fv := v.FieldByName(f.Name)

switch fv.Kind() {
case reflect.Array:
case reflect.Interface:
case reflect.Slice:
case reflect.Struct:
if reflect.DeepEqual(v.Interface(), fv.Interface()) {
continue
}
}

if len(f.Tag) > 0 {
err = append(err, validateField(f, v.FieldByName(f.Name))...)
}
}

return len(err) == 0, err
}

func validateField(f reflect.StructField, v reflect.Value) []error {
var err []error

if f.Type.Kind() == reflect.Struct {
_, errs := Validate(v.Interface())
return errs
}

for tag, validate := range validatorFuncs {
if len(f.Tag.Get(tag)) > 0 {
if e := validate(f.Name, f.Tag.Get(tag), v); e != nil {
err = append(err, e)
}
}
}

return err
}
40 changes: 40 additions & 0 deletions validate/validate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package validate

import (
"errors"
"testing"
)

type testStruct struct {
String string `minLen:"10" maxLen:"50"`
Int int `min:"5"`
Error error `nil:"false"`
}

func TestValidate(t *testing.T) {
s := &testStruct{
String: "abcdefabcdef",
Int: 10,
Error: errors.New("test"),
}
if _, errs := Validate(s); len(errs) > 0 {
t.Errorf("Number of errors did not match. Got %d, expected 0", len(errs))
for _, err := range errs {
t.Errorf(" %s", err.Error())
}
}
}

func TestValidate_Errors(t *testing.T) {
s := &testStruct{
String: "abc",
Int: 0,
Error: nil,
}
if _, errs := Validate(s); len(errs) != 3 {
t.Errorf("Number of errors did not match. Got %d, expected 3", len(errs))
for _, err := range errs {
t.Errorf(" %s", err.Error())
}
}
}
77 changes: 77 additions & 0 deletions validate/validators/length.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package validators

import (
"fmt"
"reflect"
"strconv"
)

// MinLen validates the length of a reflect.Value to be at least
// the value of tag.
func MinLen(name string, tag string, v reflect.Value) error {
min, err := strconv.ParseInt(tag, 10, 32)
if err != nil {
return fmt.Errorf(
"The tag %#q could not be converted to a numeric value",
tag,
)
}

switch v.Kind() {
case reflect.Array:
case reflect.Slice:
if len(v.Interface().([]interface{})) < int(min) {
return fmt.Errorf("Value %#q is shorter than %d", name, min)
}
return nil

case reflect.Map:
if len(v.Interface().(map[interface{}]interface{})) < int(min) {
return fmt.Errorf("Value %#q is shorter than %d", name, min)
}
return nil

case reflect.String:
if len(v.Interface().(string)) < int(min) {
return fmt.Errorf("Value %#q is shorter than %d", name, min)
}
return nil
}

return fmt.Errorf("Value %#q cannot be checked for length", name)
}

// MaxLen validates the length of a reflect.Value to be no higher than
// the value of tag.
func MaxLen(name string, tag string, v reflect.Value) error {
max, err := strconv.ParseInt(tag, 10, 32)
if err != nil {
return fmt.Errorf(
"The tag %#q could not be converted to a numeric value",
tag,
)
}

switch v.Kind() {
case reflect.Array:
case reflect.Slice:
if len(v.Interface().([]interface{})) > int(max) {
return fmt.Errorf("Value %#q is longer than %d", name, max)
}
return nil

case reflect.Map:
if len(v.Interface().(map[interface{}]interface{})) > int(max) {
return fmt.Errorf("Value %#q is longer than %d", name, max)
}
return nil

case reflect.String:
if len(v.Interface().(string)) > int(max) {
return fmt.Errorf("Value %#q is longer than %d", name, max)
}
return nil
}

return fmt.Errorf("Value %#q cannot be checked for length", name)
}
Loading

0 comments on commit c9ec2e3

Please sign in to comment.