diff --git a/README.md b/README.md index 7b45b1b..db03584 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Package validator ================ [![Join the chat at https://gitter.im/go-playground/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -![Project status](https://img.shields.io/badge/version-9.27.0-green.svg) +![Project status](https://img.shields.io/badge/version-9.28.0-green.svg) [![Build Status](https://semaphoreci.com/api/v1/joeybloggs/validator/branches/v9/badge.svg)](https://semaphoreci.com/joeybloggs/validator) [![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=v9&service=github)](https://coveralls.io/github/go-playground/validator?branch=v9) [![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator) diff --git a/baked_in.go b/baked_in.go index 52729b8..702e78d 100644 --- a/baked_in.go +++ b/baked_in.go @@ -112,6 +112,8 @@ var ( "excludes": excludes, "excludesall": excludesAll, "excludesrune": excludesRune, + "startswith": startsWith, + "endswith": endsWith, "isbn": isISBN, "isbn10": isISBN10, "isbn13": isISBN13, @@ -650,6 +652,16 @@ func contains(fl FieldLevel) bool { return strings.Contains(fl.Field().String(), fl.Param()) } +// StartsWith is the validation function for validating that the field's value starts with the text specified within the param. +func startsWith(fl FieldLevel) bool { + return strings.HasPrefix(fl.Field().String(), fl.Param()) +} + +// EndsWith is the validation function for validating that the field's value ends with the text specified within the param. +func endsWith(fl FieldLevel) bool { + return strings.HasSuffix(fl.Field().String(), fl.Param()) +} + // FieldContains is the validation function for validating if the current field's value contains the field specified by the param's value. func fieldContains(fl FieldLevel) bool { field := fl.Field() diff --git a/doc.go b/doc.go index 0bc27a1..40db7c4 100644 --- a/doc.go +++ b/doc.go @@ -714,6 +714,18 @@ This validates that a string value does not contain the supplied rune value. Usage: excludesrune=@ +Starts With + +This validates that a string value starts with the supplied string value + + Usage: startswith=hello + +Ends With + +This validates that a string value ends with the supplied string value + + Usage: endswith=goodbye + International Standard Book Number This validates that a string value contains a valid isbn10 or isbn13 value. @@ -734,25 +746,25 @@ This validates that a string value contains a valid isbn13 value. Universally Unique Identifier UUID -This validates that a string value contains a valid UUID. +This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead. Usage: uuid Universally Unique Identifier UUID v3 -This validates that a string value contains a valid version 3 UUID. +This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead. Usage: uuid3 Universally Unique Identifier UUID v4 -This validates that a string value contains a valid version 4 UUID. +This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead. Usage: uuid4 Universally Unique Identifier UUID v5 -This validates that a string value contains a valid version 5 UUID. +This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead. Usage: uuid5 @@ -998,5 +1010,30 @@ that should not make it to production. } validate.Struct(t) // this will panic + +Non standard validators + +A collection of validation rules that are frequently needed but are more +complex than the ones found in the baked in validators. +A non standard validator must be registered manually using any tag you like. +See below examples of registration and use. + + type Test struct { + TestField string `validate:"yourtag"` + } + + t := &Test{ + TestField: "Test" + } + + validate := validator.New() + validate.RegisterValidation("yourtag", validations.ValidatorName) + + NotBlank + This validates that the value is not blank or with length zero. + For strings ensures they do not contain only spaces. For channels, maps, slices and arrays + ensures they don't have zero length. For others, a non empty value is required. + + Usage: notblank */ package validator diff --git a/non-standard/validators/notblank.go b/non-standard/validators/notblank.go new file mode 100644 index 0000000..5c2d806 --- /dev/null +++ b/non-standard/validators/notblank.go @@ -0,0 +1,25 @@ +package validators + +import ( + "reflect" + "strings" + + "github.com/andreiavrammsd/validator" +) + +// NotBlank is the validation function for validating if the current field +// has a value or length greater than zero, or is not a space only string. +func NotBlank(fl validator.FieldLevel) bool { + field := fl.Field() + + switch field.Kind() { + case reflect.String: + return len(strings.TrimSpace(field.String())) > 0 + case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: + return field.Len() > 0 + case reflect.Ptr, reflect.Interface, reflect.Func: + return !field.IsNil() + default: + return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() + } +} diff --git a/non-standard/validators/notblank_test.go b/non-standard/validators/notblank_test.go new file mode 100644 index 0000000..1eecae6 --- /dev/null +++ b/non-standard/validators/notblank_test.go @@ -0,0 +1,65 @@ +package validators + +import ( + "testing" + + "github.com/andreiavrammsd/validator" + "gopkg.in/go-playground/assert.v1" +) + +type test struct { + String string `validate:"notblank"` + Array []int `validate:"notblank"` + Pointer *int `validate:"notblank"` + Number int `validate:"notblank"` + Interface interface{} `validate:"notblank"` + Func func() `validate:"notblank"` +} + +func TestNotBlank(t *testing.T) { + v := validator.New() + err := v.RegisterValidation("notblank", NotBlank) + assert.Equal(t, nil, err) + + // Errors + var x *int + invalid := test{ + String: " ", + Array: []int{}, + Pointer: x, + Number: 0, + Interface: nil, + Func: nil, + } + fieldsWithError := []string{ + "String", + "Array", + "Pointer", + "Number", + "Interface", + "Func", + } + + errors := v.Struct(invalid).(validator.ValidationErrors) + var fields []string + for _, err := range errors { + fields = append(fields, err.Field()) + } + + assert.Equal(t, fieldsWithError, fields) + + // No errors + y := 1 + x = &y + valid := test{ + String: "str", + Array: []int{1}, + Pointer: x, + Number: 1, + Interface: "value", + Func: func() {}, + } + + err = v.Struct(valid) + assert.Equal(t, nil, err) +} diff --git a/regexes.go b/regexes.go index 71ccd97..0253d70 100644 --- a/regexes.go +++ b/regexes.go @@ -15,7 +15,7 @@ const ( rgbaRegexString = "^rgba\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\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7 @@ const ( dataURIRegexString = "^data:.+\\/(.+);base64$" latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - sSNRegexString = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` + sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$` hostnameRegexStringRFC952 = `^[a-zA-Z][a-zA-Z0-9\-\.]+[a-zA-Z0-9]$` // https://tools.ietf.org/html/rfc952 hostnameRegexStringRFC1123 = `^[a-zA-Z0-9][a-zA-Z0-9\-\.]+[a-zA-Z0-9]$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123 btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address diff --git a/validator_test.go b/validator_test.go index 46e67da..10e062e 100644 --- a/validator_test.go +++ b/validator_test.go @@ -6535,6 +6535,15 @@ func TestEmail(t *testing.T) { NotEqual(t, errs, nil) AssertError(t, errs, "", "", "", "", "email") + s = `"test test"@email.com` + errs = validate.Var(s, "email") + Equal(t, errs, nil) + + s = `"@email.com` + errs = validate.Var(s, "email") + NotEqual(t, errs, nil) + AssertError(t, errs, "", "", "", "", "email") + i := true errs = validate.Var(i, "email") NotEqual(t, errs, nil) @@ -8556,3 +8565,59 @@ func TestDirValidation(t *testing.T) { validate.Var(2, "dir") }, "Bad field type int") } + +func TestStartsWithValidation(t *testing.T) { + tests := []struct { + Value string `validate:"startswith=(/^ヮ^)/*:・゚✧"` + Tag string + ExpectedNil bool + }{ + {Value: "(/^ヮ^)/*:・゚✧ glitter", Tag: "startswith=(/^ヮ^)/*:・゚✧", ExpectedNil: true}, + {Value: "abcd", Tag: "startswith=(/^ヮ^)/*:・゚✧", ExpectedNil: false}, + } + + validate := New() + + for i, s := range tests { + errs := validate.Var(s.Value, s.Tag) + + if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) { + t.Fatalf("Index: %d failed Error: %s", i, errs) + } + + errs = validate.Struct(s) + + if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) { + t.Fatalf("Index: %d failed Error: %s", i, errs) + } + } +} + +func TestEndsWithValidation(t *testing.T) { + tests := []struct { + Value string `validate:"endswith=(/^ヮ^)/*:・゚✧"` + Tag string + ExpectedNil bool + }{ + {Value: "glitter (/^ヮ^)/*:・゚✧", Tag: "endswith=(/^ヮ^)/*:・゚✧", ExpectedNil: true}, + {Value: "(/^ヮ^)/*:・゚✧ glitter", Tag: "endswith=(/^ヮ^)/*:・゚✧", ExpectedNil: false}, + } + + validate := New() + + for i, s := range tests { + errs := validate.Var(s.Value, s.Tag) + + if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) { + t.Fatalf("Index: %d failed Error: %s", i, errs) + } + + errs = validate.Struct(s) + + if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) { + t.Fatalf("Index: %d failed Error: %s", i, errs) + } + } +} + +