Last active
August 29, 2015 14:12
-
-
Save vladvelici/00679f8dff9e205cc157 to your computer and use it in GitHub Desktop.
This is an example usage of the github.com/vladvelici/valid package.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example code for a simple custom validator using github.com/vladvelici/valid | |
// | |
// This program outputs: | |
// | |
// $ ./valid-example hello | |
// Validation result: 2 errors. | |
// 1. Not "example" (case-insensitive). | |
// 2. Not exactly "example". | |
// | |
// $ ./valid-example example | |
// Validation result: 0 errors. | |
// | |
// $ ./valid-example examplE | |
// Validation result: 1 errors. | |
// 1. Not exactly "example". | |
package main | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
"github.com/vladvelici/valid" | |
) | |
// This validator checks whether the given string is | |
// Param in a case-insensitive way. | |
type MyValidator struct { | |
Param string | |
} | |
// Validate method. | |
func (v *MyValidator) Validate(value string) error { | |
if strings.ToLower(value) != strings.ToLower(v.Param) { | |
return fmt.Errorf("Not %#v (case-insensitive).", v.Param) | |
} | |
return nil | |
} | |
// This program validates the first command line argument (after program name), | |
// using two custom built validators: | |
// | |
// - one performs case-insensitive comparision with a parameter | |
// - one performs case-sensitive comparison | |
// | |
// The parameter is defined above to have the value "example" | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("Not enough arguments.") | |
return | |
} | |
arg := os.Args[1] | |
parameter := "example" | |
// our case-insensitive validator | |
ci := &MyValidator{parameter} | |
// define an inline, case-sensitive validator, to demonstrate usage of | |
// valid.StringFunc type. | |
cs := func(val string) error { | |
if val != parameter { | |
return fmt.Errorf("Not exactly %#v.", parameter) | |
} | |
return nil | |
} | |
// apply validation using the two validators | |
errs := valid.String(arg, ci, valid.StringFunc(cs)) | |
fmt.Printf("Validation result: %d errors.\n", len(errs)) | |
for i, e := range errs { | |
fmt.Printf("%d. %s\n", i+1, e.Error()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment