-
-
Save cbluth/60b245fdc7bfd91a3ce49c6b8d36d764 to your computer and use it in GitHub Desktop.
Golang Custom Validator examples
This file contains hidden or 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
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:"[email protected]", 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