From cf8445ca81206fc6c8a231f9b7ff8eecf0fd4cdf Mon Sep 17 00:00:00 2001 From: Saddam H Date: Sun, 23 Sep 2018 15:23:03 +0600 Subject: [PATCH] Add alpha_space and fix typo (#42) * Changed from max to min in the README.md. Seems to have been a typo. (#38) * Fixed a couple of typos. (#39) * Changed from max to min in the README.md. Seems to have been a typo. * Fixed a couple of typos. * Add new rule alpha_space (#41) * Add new rule alpha_space * use gofmt * Fix typo --- README.md | 3 ++- doc/SIMPLE_STRUCT_VALIDATION.md | 4 ++-- helper.go | 5 +++++ regex_patterns.go | 12 +++++----- rules.go | 13 +++++++++++ rules_test.go | 39 +++++++++++++++++++++++++++++++++ 6 files changed, 68 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 11eff74..d06d4ec 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,7 @@ Send request to the server using curl or postman: `curl GET "http://localhost:90 ### Validation Rules * `alpha` The field under validation must be entirely alphabetic characters. * `alpha_dash` The field under validation may have alpha-numeric characters, as well as dashes and underscores. +* `alpha_space` The field under validation may have alpha-numeric characters, as well as dashes, underscores and space. * `alpha_num` The field under validation must be entirely alpha-numeric characters. * `between:numeric,numeric` The field under validation check the length of characters/ length of array, slice, map/ range between two integer or float number etc. * `numeric` The field under validation must be entirely numeric characters. @@ -145,7 +146,7 @@ Send request to the server using curl or postman: `curl GET "http://localhost:90 * `not_in:foo,bar` The field under validation must have one value except foo,bar. e.g: `not_in:admin,manager,user` must not contain the values (admin or manager or user) * `email` The field under validation must have a valid email. * `float` The field under validation must have a valid float number. -* `max:numeric` The field under validation must have a min length of characters for string, items length for slice/map, value for integer or float. +* `min:numeric` The field under validation must have a min length of characters for string, items length for slice/map, value for integer or float. e.g: `min:3` may contains characters minimum length of 3 like `"john", "jane", "jane321"` but not `"mr", "xy"` * `max:numeric` The field under validation must have a max length of characters for string, items length for slice/map, value for integer or float. e.g: `max:6` may contains characters maximum length of 6 like `"john doe", "jane doe"` but not `"john", "jane"` diff --git a/doc/SIMPLE_STRUCT_VALIDATION.md b/doc/SIMPLE_STRUCT_VALIDATION.md index be9e8f6..ff73afb 100644 --- a/doc/SIMPLE_STRUCT_VALIDATION.md +++ b/doc/SIMPLE_STRUCT_VALIDATION.md @@ -42,7 +42,7 @@ func handler(w http.ResponseWriter, r *http.Request) { e := v.ValidateJSON() fmt.Println(user) // your incoming JSON data in Go data struct err := map[string]interface{}{"validationError": e} - w.Header().Set("Content-type", "applciation/json") + w.Header().Set("Content-type", "application/json") json.NewEncoder(w).Encode(err) } @@ -53,7 +53,7 @@ func main() { } ``` -***Resposne*** +***Response*** ```json { "validationError": { diff --git a/helper.go b/helper.go index e4b3f1f..9cb02b8 100644 --- a/helper.go +++ b/helper.go @@ -15,6 +15,11 @@ func isAlphaDash(str string) bool { return regexAlphaDash.MatchString(str) } +// isAlphaSpace check the input is letters, number with dash and underscore +func isAlphaSpace(str string) bool { + return regexAlphaSpace.MatchString(str) +} + // isAlphaNumeric check the input is alpha numeric or not func isAlphaNumeric(str string) bool { return regexAlphaNumeric.MatchString(str) diff --git a/regex_patterns.go b/regex_patterns.go index bdb5f2b..e202cdc 100644 --- a/regex_patterns.go +++ b/regex_patterns.go @@ -5,11 +5,12 @@ import ( ) const ( - // Alpha represents regular expression for alpha chartacters + // Alpha represents regular expression for alpha characters Alpha string = "^[a-zA-Z]+$" - // AlphaDash represents regular expression for alpha chartacters with underscore and ash - AlphaDash string = "^[a-zA-Z0-9_-]+$" - // AlphaNumeric represents regular expression for alpha numeric chartacters + // AlphaDash represents regular expression for alpha characters with underscore and dash + AlphaDash string = "^[a-zA-Z0-9_-]+$" + AlphaSpace string = "^[-a-zA-Z0-9_ ]+$" + // AlphaNumeric represents regular expression for alpha numeric characters AlphaNumeric string = "^[a-zA-Z0-9]+$" // CreditCard represents regular expression for credit cards like (Visa, MasterCard, American Express, Diners Club, Discover, and JCB cards). Ref: https://stackoverflow.com/questions/9315647/regex-credit-card-number-tests CreditCard string = "^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$" @@ -23,7 +24,7 @@ const ( DateDDMMYY string = "^(0?[1-9]|[12][0-9]|3[01])[\\/\\-](0?[1-9]|1[012])[\\/\\-]\\d{4}$" // Email represents regular expression for email Email string = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$" - // Float represents regular expression for finding fload number + // Float represents regular expression for finding float number Float string = "^[+-]?([0-9]*[.])?[0-9]+$" // IP represents regular expression for ip address IP string = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$" @@ -52,6 +53,7 @@ const ( var ( regexAlpha = regexp.MustCompile(Alpha) regexAlphaDash = regexp.MustCompile(AlphaDash) + regexAlphaSpace = regexp.MustCompile(AlphaSpace) regexAlphaNumeric = regexp.MustCompile(AlphaNumeric) regexCreditCard = regexp.MustCompile(CreditCard) regexCoordinate = regexp.MustCompile(Coordinate) diff --git a/rules.go b/rules.go index 45e74dd..e137129 100644 --- a/rules.go +++ b/rules.go @@ -194,6 +194,19 @@ func init() { return nil }) + // AlphaDash check if provided field contains valid letters, numbers, underscore and dash + AddCustomRule("alpha_space", func(field string, vlaue string, message string, value interface{}) error { + str := toString(value) + err := fmt.Errorf("The %s may only contain letters, numbers, dashes, space", field) + if message != "" { + err = errors.New(message) + } + if !isAlphaSpace(str) { + return err + } + return nil + }) + // AlphaNumeric check if provided field contains valid letters and numbers AddCustomRule("alpha_num", func(field string, vlaue string, message string, value interface{}) error { str := toString(value) diff --git a/rules_test.go b/rules_test.go index 7de69d7..42f471b 100644 --- a/rules_test.go +++ b/rules_test.go @@ -232,6 +232,45 @@ func Test_AlphaDash(t *testing.T) { } } +func Test_AlphaSpace(t *testing.T) { + type user struct { + Name string `json:"name"` + } + + postUser := user{Name: "999$"} + var userObj user + + body, _ := json.Marshal(postUser) + req, _ := http.NewRequest("POST", "http://www.example.com", bytes.NewReader(body)) + + messages := MapData{ + "name": []string{"alpha_space:custom_message"}, + } + + rules := MapData{ + "name": []string{"alpha_space"}, + } + + opts := Options{ + Request: req, + Data: &userObj, + Rules: rules, + Messages: messages, + } + + vd := New(opts) + validationErr := vd.ValidateJSON() + t.Log(len(validationErr)) + if len(validationErr) != 1 { + t.Log(validationErr) + t.Error("alpha_space validation failed!") + } + + if validationErr.Get("name") != "custom_message" { + t.Error("alpha space custom message failed!") + } +} + func Test_AlphaNumeric(t *testing.T) { type user struct { Name string `json:"name"`