Skip to content

Instantly share code, notes, and snippets.

@dakait dakait/validators.go
Last active Aug 28, 2018

Embed
What would you like to do?
Golang Custom Validator examples
package main
import (
"fmt"
"github.com/satori/go.uuid" //for uuid
"gopkg.in/validator.v2"
"reflect"
"regexp"
"time"
)
const regexEmail string = `(?m)^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$`
type Data struct {
Token string `json:"token" validate:"tokenvalidator"`
Email string `json:"email" validate:"nonzero,emailvalidator"`
CreatedOn time.Time `json:"created_on" validate:"datevalidator"`
}
//EmailValidator checks if email is valid using regex defined globally
func EmailValidator(v interface{}, param string) error {
st := reflect.ValueOf(v)
if st.Kind() != reflect.String {
return validator.ErrBadParameter
}
re := regexp.MustCompile(regexEmail)
if re.MatchString(v.(string)) == false {
return validator.ErrRegexp
}
return nil
}
//TokenValidator checks if token is valid UUID
func TokenValidator(v interface{}, param string) error {
st := reflect.ValueOf(v)
if st.Kind() != reflect.String {
return validator.ErrBadParameter
}
_, err := uuid.FromString(v.(string))
if err != nil {
return validator.ErrInvalid
}
return nil
}
//DateValidator checks if date provided is not less than today's date
func DateValidator(v interface{}, param string) error {
st := reflect.ValueOf(v)
if date, ok:= st.Interface().(time.Time); ok {
today := time.Now()
if today.Year() > date.Year() || today.YearDay() > date.YearDay(){
return validator.ErrInvalid
}
} else {
return validator.ErrUnsupported
}
return nil
}
func main() {
validator.SetValidationFunc("emailvalidator", EmailValidator)
validator.SetValidationFunc("tokenvalidator", TokenValidator)
validator.SetValidationFunc("datevalidator", DateValidator)
test := &Data{Token:"b85d3fe4-aaac-11e8-96b2-74d4354af7d2", Email:"example@xyz.com", CreatedOn:time.Now()}
if err := validator.Validate(test); err == nil {
fmt.Println("Validated.")
} else {
fmt.Println(err.Error())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.