From bef6bca3973f4e12cefa31d44ec104021f05850c Mon Sep 17 00:00:00 2001 From: miraclesu Date: Tue, 5 Jan 2016 21:14:35 +0800 Subject: [PATCH] Add function to set validation default messages --- validation/README.md | 2 +- validation/validation.go | 2 +- validation/validators.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/validation/README.md b/validation/README.md index e0c30df7..b4fc3fe5 100644 --- a/validation/README.md +++ b/validation/README.md @@ -41,7 +41,7 @@ Direct Use: } } // or use like this - if v := valid.Max(u.Age, 140); !v.Ok { + if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } diff --git a/validation/validation.go b/validation/validation.go index 76683d91..2b020aa8 100644 --- a/validation/validation.go +++ b/validation/validation.go @@ -38,7 +38,7 @@ // } // } // // or use like this -// if v := valid.Max(u.Age, 140); !v.Ok { +// if v := valid.Max(u.Age, 140, "ageMax"); !v.Ok { // log.Println(v.Error.Key, v.Error.Message) // } // } diff --git a/validation/validators.go b/validation/validators.go index 2662b701..7e1822cf 100644 --- a/validation/validators.go +++ b/validation/validators.go @@ -46,6 +46,38 @@ var MessageTmpls = map[string]string{ "ZipCode": "Must be valid zipcode", } +// set default messages +// if not set, the default messages are +// "Required": "Can not be empty", +// "Min": "Minimum is %d", +// "Max": "Maximum is %d", +// "Range": "Range is %d to %d", +// "MinSize": "Minimum size is %d", +// "MaxSize": "Maximum size is %d", +// "Length": "Required length is %d", +// "Alpha": "Must be valid alpha characters", +// "Numeric": "Must be valid numeric characters", +// "AlphaNumeric": "Must be valid alpha or numeric characters", +// "Match": "Must match %s", +// "NoMatch": "Must not match %s", +// "AlphaDash": "Must be valid alpha or numeric or dash(-_) characters", +// "Email": "Must be a valid email address", +// "IP": "Must be a valid ip address", +// "Base64": "Must be valid base64 characters", +// "Mobile": "Must be valid mobile number", +// "Tel": "Must be valid telephone number", +// "Phone": "Must be valid telephone or mobile phone number", +// "ZipCode": "Must be valid zipcode", +func SetDefaultMessage(msg map[string]string) { + if len(msg) == 0 { + return + } + + for name := range msg { + MessageTmpls[name] = msg[name] + } +} + // Validator interface type Validator interface { IsSatisfied(interface{}) bool