From da76950858b3852fab2924969f6d1c47d43c7163 Mon Sep 17 00:00:00 2001 From: Onur Cinar Date: Tue, 29 Oct 2024 19:46:44 -0700 Subject: [PATCH] Checker errors are converted from string to error. (#124) # Describe Request Checker errors are converted from string to error. # Change Type New feature. --- alphanumeric.go | 13 +++---- alphanumeric_test.go | 9 +++-- ascii.go | 13 +++---- ascii_test.go | 9 +++-- checker.go | 30 +++++++---------- checker_test.go | 10 +++--- cidr.go | 13 +++---- cidr_test.go | 9 +++-- credit_card.go | 33 +++++++++--------- credit_card_test.go | 80 ++++++++++++++++++++++---------------------- digits.go | 13 +++---- digits_test.go | 9 +++-- email.go | 33 +++++++++--------- email_test.go | 9 +++-- fqdn.go | 25 +++++++------- fqdn_test.go | 23 ++++++------- html_escape.go | 4 +-- html_escape_test.go | 1 - html_unescape.go | 4 +-- ip.go | 13 +++---- ip_test.go | 9 +++-- ipv4.go | 15 +++++---- ipv4_test.go | 11 +++--- ipv6.go | 15 +++++---- ipv6_test.go | 10 +++--- isbn.go | 29 ++++++++-------- isbn_test.go | 61 ++++++++++++++++----------------- lower.go | 4 +-- lower_test.go | 2 +- luhn.go | 13 +++---- luhn_test.go | 7 ++-- mac.go | 13 +++---- mac_test.go | 9 +++-- max.go | 14 ++++---- max_test.go | 7 ++-- maxlength.go | 14 ++++---- maxlength_test.go | 7 ++-- min.go | 14 ++++---- min_test.go | 7 ++-- minlenght.go | 14 ++++---- minlength_test.go | 7 ++-- regexp.go | 23 +++++++------ regexp_test.go | 9 ++--- required.go | 19 ++++++----- required_test.go | 30 ++++++++--------- same.go | 13 +++---- title.go | 4 +-- title_test.go | 2 +- trim.go | 4 +-- trim_left.go | 4 +-- trim_left_test.go | 2 +- trim_right.go | 4 +-- trim_right_test.go | 2 +- trim_test.go | 2 +- upper.go | 4 +-- upper_test.go | 2 +- url.go | 17 +++++----- url_escape.go | 4 +-- url_test.go | 12 +++---- url_unescape.go | 4 +-- 60 files changed, 394 insertions(+), 402 deletions(-) diff --git a/alphanumeric.go b/alphanumeric.go index 9ef41c9..8b87ace 100644 --- a/alphanumeric.go +++ b/alphanumeric.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "unicode" ) @@ -13,18 +14,18 @@ import ( // CheckerAlphanumeric is the name of the checker. const CheckerAlphanumeric = "alphanumeric" -// ResultNotAlphanumeric indicates that the given string contains non-alphanumeric characters. -const ResultNotAlphanumeric = "NOT_ALPHANUMERIC" +// ErrNotAlphanumeric indicates that the given string contains non-alphanumeric characters. +var ErrNotAlphanumeric = errors.New("please use only letters and numbers") // IsAlphanumeric checks if the given string consists of only alphanumeric characters. -func IsAlphanumeric(value string) Result { +func IsAlphanumeric(value string) error { for _, c := range value { if !unicode.IsDigit(c) && !unicode.IsLetter(c) { - return ResultNotAlphanumeric + return ErrNotAlphanumeric } } - return ResultValid + return nil } // makeAlphanumeric makes a checker function for the alphanumeric checker. @@ -33,7 +34,7 @@ func makeAlphanumeric(_ string) CheckFunc { } // checkAlphanumeric checks if the given string consists of only alphanumeric characters. -func checkAlphanumeric(value, _ reflect.Value) Result { +func checkAlphanumeric(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/alphanumeric_test.go b/alphanumeric_test.go index 9e92fa7..4fe9661 100644 --- a/alphanumeric_test.go +++ b/alphanumeric_test.go @@ -12,21 +12,20 @@ import ( ) func ExampleIsAlphanumeric() { - result := checker.IsAlphanumeric("ABcd1234") - - if result != checker.ResultValid { + err := checker.IsAlphanumeric("ABcd1234") + if err != nil { // Send the mistakes back to the user } } func TestIsAlphanumericInvalid(t *testing.T) { - if checker.IsAlphanumeric("-/") == checker.ResultValid { + if checker.IsAlphanumeric("-/") == nil { t.Fail() } } func TestIsAlphanumericValid(t *testing.T) { - if checker.IsAlphanumeric("ABcd1234") != checker.ResultValid { + if checker.IsAlphanumeric("ABcd1234") != nil { t.Fail() } } diff --git a/ascii.go b/ascii.go index 452b075..32f68a2 100644 --- a/ascii.go +++ b/ascii.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "unicode" ) @@ -13,18 +14,18 @@ import ( // CheckerASCII is the name of the checker. const CheckerASCII = "ascii" -// ResultNotASCII indicates that the given string contains non-ASCII characters. -const ResultNotASCII = "NOT_ASCII" +// ErrNotASCII indicates that the given string contains non-ASCII characters. +var ErrNotASCII = errors.New("please use standard English characters only") // IsASCII checks if the given string consists of only ASCII characters. -func IsASCII(value string) Result { +func IsASCII(value string) error { for _, c := range value { if c > unicode.MaxASCII { - return ResultNotASCII + return ErrNotASCII } } - return ResultValid + return nil } // makeASCII makes a checker function for the ASCII checker. @@ -33,7 +34,7 @@ func makeASCII(_ string) CheckFunc { } // checkASCII checks if the given string consists of only ASCII characters. -func checkASCII(value, _ reflect.Value) Result { +func checkASCII(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/ascii_test.go b/ascii_test.go index fa2f5e4..8685362 100644 --- a/ascii_test.go +++ b/ascii_test.go @@ -12,21 +12,20 @@ import ( ) func ExampleIsASCII() { - result := checker.IsASCII("Checker") - - if result != checker.ResultValid { + err := checker.IsASCII("Checker") + if err != nil { // Send the mistakes back to the user } } func TestIsASCIIInvalid(t *testing.T) { - if checker.IsASCII("𝄞 Music!") == checker.ResultValid { + if checker.IsASCII("𝄞 Music!") == nil { t.Fail() } } func TestIsASCIIValid(t *testing.T) { - if checker.IsASCII("Checker") != checker.ResultValid { + if checker.IsASCII("Checker") != nil { t.Fail() } } diff --git a/checker.go b/checker.go index 4e4436f..afbef50 100644 --- a/checker.go +++ b/checker.go @@ -12,17 +12,14 @@ import ( "strings" ) -// Result is a unique textual identifier for the mistake. -type Result string +// CheckFunc defines the signature for the checker functions. +type CheckFunc func(value, parent reflect.Value) error -// CheckFunc defines the checker function. -type CheckFunc func(value, parent reflect.Value) Result - -// MakeFunc defines the maker function. +// MakeFunc defines the signature for the checker maker functions. type MakeFunc func(params string) CheckFunc -// Mistakes provides mapping to checker result for the invalid fields. -type Mistakes map[string]Result +// Errors provides a mapping of the checker errors keyed by the field names. +type Errors map[string]error type checkerJob struct { Parent reflect.Value @@ -31,10 +28,7 @@ type checkerJob struct { Config string } -// ResultValid result indicates that the user input is valid. -const ResultValid Result = "VALID" - -// makers provides mapping to maker function for the checkers. +// makers provides a mapping of the maker functions keyed by the respective checker names. var makers = map[string]MakeFunc{ CheckerAlphanumeric: makeAlphanumeric, CheckerASCII: makeASCII, @@ -74,14 +68,14 @@ func Register(name string, maker MakeFunc) { makers[name] = maker } -// Check checks the given struct based on the checkers listed in each field's strcut tag named checkers. -func Check(s interface{}) (Mistakes, bool) { +// Check function checks the given struct based on the checkers listed in field tag names. +func Check(s interface{}) (Errors, bool) { root := reflect.Indirect(reflect.ValueOf(s)) if root.Kind() != reflect.Struct { panic("expecting struct") } - mistakes := Mistakes{} + errors := Errors{} jobs := []checkerJob{ { @@ -123,15 +117,15 @@ func Check(s interface{}) (Mistakes, bool) { } } else { for _, checker := range initCheckers(job.Config) { - if result := checker(job.Value, job.Parent); result != ResultValid { - mistakes[job.Name] = result + if err := checker(job.Value, job.Parent); err != nil { + errors[job.Name] = err break } } } } - return mistakes, len(mistakes) == 0 + return errors, len(errors) == 0 } // initCheckers initializes the checkers provided in the config. diff --git a/checker_test.go b/checker_test.go index 1a39146..723a9e6 100644 --- a/checker_test.go +++ b/checker_test.go @@ -30,8 +30,8 @@ func TestInitCheckersKnwon(t *testing.T) { } func TestRegister(t *testing.T) { - var checker CheckFunc = func(_, _ reflect.Value) Result { - return ResultValid + var checker CheckFunc = func(_, _ reflect.Value) error { + return nil } var maker MakeFunc = func(_ string) CheckFunc { @@ -69,7 +69,7 @@ func TestCheckInvalid(t *testing.T) { t.Fail() } - if mistakes["Name"] != ResultRequired { + if mistakes["Name"] != ErrRequired { t.Fail() } } @@ -121,11 +121,11 @@ func TestCheckNestedStruct(t *testing.T) { t.Fail() } - if mistakes["Name"] != ResultRequired { + if mistakes["Name"] != ErrRequired { t.Fail() } - if mistakes["Home.Street"] != ResultRequired { + if mistakes["Home.Street"] != ErrRequired { t.Fail() } } diff --git a/cidr.go b/cidr.go index 4276a8a..275427c 100644 --- a/cidr.go +++ b/cidr.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "net" "reflect" ) @@ -13,17 +14,17 @@ import ( // CheckerCidr is the name of the checker. const CheckerCidr = "cidr" -// ResultNotCidr indicates that the given value is not a valid CIDR. -const ResultNotCidr = "NOT_CIDR" +// ErrNotCidr indicates that the given value is not a valid CIDR. +var ErrNotCidr = errors.New("please enter a valid CIDR") // IsCidr checker checks if the value is a valid CIDR notation IP address and prefix length. -func IsCidr(value string) Result { +func IsCidr(value string) error { _, _, err := net.ParseCIDR(value) if err != nil { - return ResultNotCidr + return ErrNotCidr } - return ResultValid + return nil } // makeCidr makes a checker function for the ip checker. @@ -32,7 +33,7 @@ func makeCidr(_ string) CheckFunc { } // checkCidr checker checks if the value is a valid CIDR notation IP address and prefix length. -func checkCidr(value, _ reflect.Value) Result { +func checkCidr(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/cidr_test.go b/cidr_test.go index 47cddc9..2dd1e38 100644 --- a/cidr_test.go +++ b/cidr_test.go @@ -12,21 +12,20 @@ import ( ) func ExampleIsCidr() { - result := checker.IsCidr("2001:db8::/32") - - if result != checker.ResultValid { + err := checker.IsCidr("2001:db8::/32") + if err != nil { // Send the mistakes back to the user } } func TestIsCidrInvalid(t *testing.T) { - if checker.IsCidr("900.800.200.100//24") == checker.ResultValid { + if checker.IsCidr("900.800.200.100//24") == nil { t.Fail() } } func TestIsCidrValid(t *testing.T) { - if checker.IsCidr("2001:db8::/32") != checker.ResultValid { + if checker.IsCidr("2001:db8::/32") != nil { t.Fail() } } diff --git a/credit_card.go b/credit_card.go index 5a4f464..9f7cc01 100644 --- a/credit_card.go +++ b/credit_card.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "regexp" "strings" @@ -14,8 +15,8 @@ import ( // CheckerCreditCard is the name of the checker. const CheckerCreditCard = "credit-card" -// ResultNotCreditCard indicates that the given value is not a valid credit card number. -const ResultNotCreditCard = "NOT_CREDIT_CARD" +// ErrNotCreditCard indicates that the given value is not a valid credit card number. +var ErrNotCreditCard = errors.New("please enter a valid credit card number") // amexExpression is the regexp for the AMEX cards. They start with 34 or 37, and has 15 digits. var amexExpression = "(?:^(?:3[47])[0-9]{13}$)" @@ -68,42 +69,42 @@ var creditCardPatterns = map[string]*regexp.Regexp{ } // IsAnyCreditCard checks if the given value is a valid credit card number. -func IsAnyCreditCard(number string) Result { +func IsAnyCreditCard(number string) error { return isCreditCard(number, anyCreditCardPattern) } // IsAmexCreditCard checks if the given valie is a valid AMEX credit card. -func IsAmexCreditCard(number string) Result { +func IsAmexCreditCard(number string) error { return isCreditCard(number, amexPattern) } // IsDinersCreditCard checks if the given valie is a valid Diners credit card. -func IsDinersCreditCard(number string) Result { +func IsDinersCreditCard(number string) error { return isCreditCard(number, dinersPattern) } // IsDiscoverCreditCard checks if the given valie is a valid Discover credit card. -func IsDiscoverCreditCard(number string) Result { +func IsDiscoverCreditCard(number string) error { return isCreditCard(number, discoverPattern) } // IsJcbCreditCard checks if the given valie is a valid JCB 15 credit card. -func IsJcbCreditCard(number string) Result { +func IsJcbCreditCard(number string) error { return isCreditCard(number, jcbPattern) } // IsMasterCardCreditCard checks if the given valie is a valid MasterCard credit card. -func IsMasterCardCreditCard(number string) Result { +func IsMasterCardCreditCard(number string) error { return isCreditCard(number, masterCardPattern) } // IsUnionPayCreditCard checks if the given valie is a valid UnionPay credit card. -func IsUnionPayCreditCard(number string) Result { +func IsUnionPayCreditCard(number string) error { return isCreditCard(number, unionPayPattern) } // IsVisaCreditCard checks if the given valie is a valid Visa credit card. -func IsVisaCreditCard(number string) Result { +func IsVisaCreditCard(number string) error { return isCreditCard(number, visaPattern) } @@ -124,7 +125,7 @@ func makeCreditCard(config string) CheckFunc { patterns = append(patterns, anyCreditCardPattern) } - return func(value, _ reflect.Value) Result { + return func(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } @@ -132,19 +133,19 @@ func makeCreditCard(config string) CheckFunc { number := value.String() for _, pattern := range patterns { - if isCreditCard(number, pattern) == ResultValid { - return ResultValid + if isCreditCard(number, pattern) == nil { + return nil } } - return ResultNotCreditCard + return ErrNotCreditCard } } // isCreditCard checks if the given number based on the given credit card pattern and the Luhn algorithm check digit. -func isCreditCard(number string, pattern *regexp.Regexp) Result { +func isCreditCard(number string, pattern *regexp.Regexp) error { if !pattern.MatchString(number) { - return ResultNotCreditCard + return ErrNotCreditCard } return IsLuhn(number) diff --git a/credit_card_test.go b/credit_card_test.go index ad2898d..f1905e8 100644 --- a/credit_card_test.go +++ b/credit_card_test.go @@ -35,206 +35,206 @@ func changeToInvalidLuhn(number string) string { } func ExampleIsAnyCreditCard() { - result := checker.IsAnyCreditCard("6011111111111117") + err := checker.IsAnyCreditCard("6011111111111117") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsAnyCreditCardValid(t *testing.T) { - if checker.IsAnyCreditCard(amexCard) != checker.ResultValid { + if checker.IsAnyCreditCard(amexCard) != nil { t.Fail() } } func TestIsAnyCreditCardInvalidPattern(t *testing.T) { - if checker.IsAnyCreditCard(invalidCard) == checker.ResultValid { + if checker.IsAnyCreditCard(invalidCard) == nil { t.Fail() } } func TestIsAnyCreditCardInvalidLuhn(t *testing.T) { - if checker.IsAnyCreditCard(changeToInvalidLuhn(amexCard)) == checker.ResultValid { + if checker.IsAnyCreditCard(changeToInvalidLuhn(amexCard)) == nil { t.Fail() } } func ExampleIsAmexCreditCard() { - result := checker.IsAmexCreditCard("378282246310005") + err := checker.IsAmexCreditCard("378282246310005") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsAmexCreditCardValid(t *testing.T) { - if checker.IsAmexCreditCard(amexCard) != checker.ResultValid { + if checker.IsAmexCreditCard(amexCard) != nil { t.Fail() } } func TestIsAmexCreditCardInvalidPattern(t *testing.T) { - if checker.IsAmexCreditCard(invalidCard) == checker.ResultValid { + if checker.IsAmexCreditCard(invalidCard) == nil { t.Fail() } } func TestIsAmexCreditCardInvalidLuhn(t *testing.T) { - if checker.IsAmexCreditCard(changeToInvalidLuhn(amexCard)) == checker.ResultValid { + if checker.IsAmexCreditCard(changeToInvalidLuhn(amexCard)) == nil { t.Fail() } } func ExampleIsDinersCreditCard() { - result := checker.IsDinersCreditCard("36227206271667") + err := checker.IsDinersCreditCard("36227206271667") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsDinersCreditCardValid(t *testing.T) { - if checker.IsDinersCreditCard(dinersCard) != checker.ResultValid { + if checker.IsDinersCreditCard(dinersCard) != nil { t.Fail() } } func TestIsDinersCreditCardInvalidPattern(t *testing.T) { - if checker.IsDinersCreditCard(invalidCard) == checker.ResultValid { + if checker.IsDinersCreditCard(invalidCard) == nil { t.Fail() } } func TestIsDinersCreditCardInvalidLuhn(t *testing.T) { - if checker.IsDinersCreditCard(changeToInvalidLuhn(dinersCard)) == checker.ResultValid { + if checker.IsDinersCreditCard(changeToInvalidLuhn(dinersCard)) == nil { t.Fail() } } func ExampleIsDiscoverCreditCard() { - result := checker.IsDiscoverCreditCard("6011111111111117") + err := checker.IsDiscoverCreditCard("6011111111111117") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsDiscoverCreditCardValid(t *testing.T) { - if checker.IsDiscoverCreditCard(discoverCard) != checker.ResultValid { + if checker.IsDiscoverCreditCard(discoverCard) != nil { t.Fail() } } func TestIsDiscoverCreditCardInvalidPattern(t *testing.T) { - if checker.IsDiscoverCreditCard(invalidCard) == checker.ResultValid { + if checker.IsDiscoverCreditCard(invalidCard) == nil { t.Fail() } } func TestIsDiscoverCreditCardInvalidLuhn(t *testing.T) { - if checker.IsDiscoverCreditCard(changeToInvalidLuhn(discoverCard)) == checker.ResultValid { + if checker.IsDiscoverCreditCard(changeToInvalidLuhn(discoverCard)) == nil { t.Fail() } } func ExampleIsJcbCreditCard() { - result := checker.IsJcbCreditCard("3530111333300000") + err := checker.IsJcbCreditCard("3530111333300000") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsJcbCreditCardValid(t *testing.T) { - if checker.IsJcbCreditCard(jcbCard) != checker.ResultValid { + if checker.IsJcbCreditCard(jcbCard) != nil { t.Fail() } } func TestIsJcbCreditCardInvalidPattern(t *testing.T) { - if checker.IsJcbCreditCard(invalidCard) == checker.ResultValid { + if checker.IsJcbCreditCard(invalidCard) == nil { t.Fail() } } func TestIsJcbCreditCardInvalidLuhn(t *testing.T) { - if checker.IsJcbCreditCard(changeToInvalidLuhn(jcbCard)) == checker.ResultValid { + if checker.IsJcbCreditCard(changeToInvalidLuhn(jcbCard)) == nil { t.Fail() } } func ExampleIsMasterCardCreditCard() { - result := checker.IsMasterCardCreditCard("5555555555554444") + err := checker.IsMasterCardCreditCard("5555555555554444") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsMasterCardCreditCardValid(t *testing.T) { - if checker.IsMasterCardCreditCard(masterCard) != checker.ResultValid { + if checker.IsMasterCardCreditCard(masterCard) != nil { t.Fail() } } func TestIsMasterCardCreditCardInvalidPattern(t *testing.T) { - if checker.IsMasterCardCreditCard(invalidCard) == checker.ResultValid { + if checker.IsMasterCardCreditCard(invalidCard) == nil { t.Fail() } } func TestIsMasterCardCreditCardInvalidLuhn(t *testing.T) { - if checker.IsMasterCardCreditCard(changeToInvalidLuhn(masterCard)) == checker.ResultValid { + if checker.IsMasterCardCreditCard(changeToInvalidLuhn(masterCard)) == nil { t.Fail() } } func ExampleIsUnionPayCreditCard() { - result := checker.IsUnionPayCreditCard("6200000000000005") + err := checker.IsUnionPayCreditCard("6200000000000005") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsUnionPayCreditCardValid(t *testing.T) { - if checker.IsUnionPayCreditCard(unionPayCard) != checker.ResultValid { + if checker.IsUnionPayCreditCard(unionPayCard) != nil { t.Fail() } } func TestIsUnionPayCreditCardInvalidPattern(t *testing.T) { - if checker.IsUnionPayCreditCard(invalidCard) == checker.ResultValid { + if checker.IsUnionPayCreditCard(invalidCard) == nil { t.Fail() } } func TestIsUnionPayCreditCardInvalidLuhn(t *testing.T) { - if checker.IsUnionPayCreditCard(changeToInvalidLuhn(unionPayCard)) == checker.ResultValid { + if checker.IsUnionPayCreditCard(changeToInvalidLuhn(unionPayCard)) == nil { t.Fail() } } func ExampleIsVisaCreditCard() { - result := checker.IsVisaCreditCard("4111111111111111") + err := checker.IsVisaCreditCard("4111111111111111") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsVisaCreditCardValid(t *testing.T) { - if checker.IsVisaCreditCard(visaCard) != checker.ResultValid { + if checker.IsVisaCreditCard(visaCard) != nil { t.Fail() } } func TestIsVisaCreditCardInvalidPattern(t *testing.T) { - if checker.IsVisaCreditCard(invalidCard) == checker.ResultValid { + if checker.IsVisaCreditCard(invalidCard) == nil { t.Fail() } } func TestIsVisaCreditCardInvalidLuhn(t *testing.T) { - if checker.IsVisaCreditCard(changeToInvalidLuhn(visaCard)) == checker.ResultValid { + if checker.IsVisaCreditCard(changeToInvalidLuhn(visaCard)) == nil { t.Fail() } } diff --git a/digits.go b/digits.go index 3ace687..9098622 100644 --- a/digits.go +++ b/digits.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "unicode" ) @@ -13,18 +14,18 @@ import ( // CheckerDigits is the name of the checker. const CheckerDigits = "digits" -// ResultNotDigits indicates that the given string contains non-digit characters. -const ResultNotDigits = "NOT_DIGITS" +// ErrNotDigits indicates that the given string contains non-digit characters. +var ErrNotDigits = errors.New("please enter a valid number") // IsDigits checks if the given string consists of only digit characters. -func IsDigits(value string) Result { +func IsDigits(value string) error { for _, c := range value { if !unicode.IsDigit(c) { - return ResultNotDigits + return ErrNotDigits } } - return ResultValid + return nil } // makeDigits makes a checker function for the digits checker. @@ -33,7 +34,7 @@ func makeDigits(_ string) CheckFunc { } // checkDigits checks if the given string consists of only digit characters. -func checkDigits(value, _ reflect.Value) Result { +func checkDigits(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/digits_test.go b/digits_test.go index 40c8f02..86830c1 100644 --- a/digits_test.go +++ b/digits_test.go @@ -12,21 +12,20 @@ import ( ) func ExampleIsDigits() { - result := checker.IsDigits("1234") - - if result != checker.ResultValid { + err := checker.IsDigits("1234") + if err != nil { // Send the mistakes back to the user } } func TestIsDigitsInvalid(t *testing.T) { - if checker.IsDigits("checker") == checker.ResultValid { + if checker.IsDigits("checker") == nil { t.Fail() } } func TestIsDigitsValid(t *testing.T) { - if checker.IsDigits("1234") != checker.ResultValid { + if checker.IsDigits("1234") != nil { t.Fail() } } diff --git a/email.go b/email.go index 6238bcf..b0ffc8f 100644 --- a/email.go +++ b/email.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "regexp" "strings" @@ -14,8 +15,8 @@ import ( // CheckerEmail is the name of the checker. const CheckerEmail = "email" -// ResultNotEmail indicates that the given string is not a valid email. -const ResultNotEmail = "NOT_EMAIL" +// ErrNotEmail indicates that the given string is not a valid email. +var ErrNotEmail = errors.New("please enter a valid email address") // ipV6Prefix is the IPv6 prefix for the domain. const ipV6Prefix = "[IPv6:" @@ -24,15 +25,15 @@ const ipV6Prefix = "[IPv6:" var notQuotedChars = regexp.MustCompile("[a-zA-Z0-9!#$%&'*\\+\\-/=?^_`{|}~]") // IsEmail checks if the given string is an email address. -func IsEmail(email string) Result { +func IsEmail(email string) error { atIndex := strings.LastIndex(email, "@") if atIndex == -1 || atIndex == len(email)-1 { - return ResultNotEmail + return ErrNotEmail } domain := email[atIndex+1:] - if isValidEmailDomain(domain) != ResultValid { - return ResultNotEmail + if isValidEmailDomain(domain) != nil { + return ErrNotEmail } return isValidEmailUser(email[:atIndex]) @@ -44,7 +45,7 @@ func makeEmail(_ string) CheckFunc { } // checkEmail checks if the given string is an email address. -func checkEmail(value, _ reflect.Value) Result { +func checkEmail(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } @@ -53,9 +54,9 @@ func checkEmail(value, _ reflect.Value) Result { } // isValidEmailDomain checks if the email domain is a IPv4 or IPv6 address, or a FQDN. -func isValidEmailDomain(domain string) Result { +func isValidEmailDomain(domain string) error { if len(domain) > 255 { - return ResultNotEmail + return ErrNotEmail } if domain[0] == '[' { @@ -72,22 +73,22 @@ func isValidEmailDomain(domain string) Result { } // isValidEmailUser checks if the email user is valid. -func isValidEmailUser(user string) Result { +func isValidEmailUser(user string) error { // Cannot be empty user if user == "" || len(user) > 64 { - return ResultNotEmail + return ErrNotEmail } // Cannot start or end with dot if user[0] == '.' || user[len(user)-1] == '.' { - return ResultNotEmail + return ErrNotEmail } return isValidEmailUserCharacters(user) } // isValidEmailUserCharacters if the email user characters are valid. -func isValidEmailUserCharacters(user string) Result { +func isValidEmailUserCharacters(user string) error { quoted := false start := true prev := ' ' @@ -95,7 +96,7 @@ func isValidEmailUserCharacters(user string) Result { for _, c := range user { // Cannot have a double dot unless quoted if !quoted && c == '.' && prev == '.' { - return ResultNotEmail + return ErrNotEmail } if start { @@ -112,7 +113,7 @@ func isValidEmailUserCharacters(user string) Result { if c == '.' { start = true } else if !notQuotedChars.MatchString(string(c)) { - return ResultNotEmail + return ErrNotEmail } } else { if c == '"' && prev != '\\' { @@ -123,5 +124,5 @@ func isValidEmailUserCharacters(user string) Result { prev = c } - return ResultValid + return nil } diff --git a/email_test.go b/email_test.go index 4460f7b..862e2ef 100644 --- a/email_test.go +++ b/email_test.go @@ -12,9 +12,8 @@ import ( ) func ExampleIsEmail() { - result := checker.IsEmail("user@zdo.com") - - if result != checker.ResultValid { + err := checker.IsEmail("user@zdo.com") + if err != nil { // Send the mistakes back to the user } } @@ -69,7 +68,7 @@ func TestIsEmailValid(t *testing.T) { } for _, email := range validEmails { - if checker.IsEmail(email) != checker.ResultValid { + if checker.IsEmail(email) != nil { t.Fatal(email) } } @@ -93,7 +92,7 @@ func TestIsEmailInvalid(t *testing.T) { } for _, email := range validEmails { - if checker.IsEmail(email) == checker.ResultValid { + if checker.IsEmail(email) == nil { t.Fatal(email) } } diff --git a/fqdn.go b/fqdn.go index 002ce19..e227260 100644 --- a/fqdn.go +++ b/fqdn.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "regexp" "strings" @@ -14,51 +15,51 @@ import ( // CheckerFqdn is the name of the checker. const CheckerFqdn = "fqdn" -// ResultNotFqdn indicates that the given string is not a valid FQDN. -const ResultNotFqdn = "NOT_FQDN" +// ErrNotFqdn indicates that the given string is not a valid FQDN. +var ErrNotFqdn = errors.New("please enter a valid domain name") // Valid characters excluding full-width characters. var fqdnValidChars = regexp.MustCompile("^[a-z0-9\u00a1-\uff00\uff06-\uffff\\-]+$") // IsFqdn checks if the given string is a fully qualified domain name. -func IsFqdn(domain string) Result { +func IsFqdn(domain string) error { parts := strings.Split(domain, ".") // Require TLD if len(parts) < 2 { - return ResultNotFqdn + return ErrNotFqdn } tld := parts[len(parts)-1] // Should be all numeric TLD - if IsDigits(tld) == ResultValid { - return ResultNotFqdn + if IsDigits(tld) == nil { + return ErrNotFqdn } // Short TLD if len(tld) < 2 { - return ResultNotFqdn + return ErrNotFqdn } for _, part := range parts { // Cannot be more than 63 characters if len(part) > 63 { - return ResultNotFqdn + return ErrNotFqdn } // Check for valid characters if !fqdnValidChars.MatchString(part) { - return ResultNotFqdn + return ErrNotFqdn } // Should not start or end with a hyphen (-) character. if part[0] == '-' || part[len(part)-1] == '-' { - return ResultNotFqdn + return ErrNotFqdn } } - return ResultValid + return nil } // makeFqdn makes a checker function for the fqdn checker. @@ -67,7 +68,7 @@ func makeFqdn(_ string) CheckFunc { } // checkFqdn checks if the given string is a fully qualified domain name. -func checkFqdn(value, _ reflect.Value) Result { +func checkFqdn(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/fqdn_test.go b/fqdn_test.go index 4e822f0..82edbfd 100644 --- a/fqdn_test.go +++ b/fqdn_test.go @@ -12,63 +12,62 @@ import ( ) func ExampleIsFqdn() { - result := checker.IsFqdn("zdo.com") - - if result != checker.ResultValid { + err := checker.IsFqdn("zdo.com") + if err != nil { // Send the mistakes back to the user } } func TestCheckFdqnWithoutTld(t *testing.T) { - if checker.IsFqdn("abcd") != checker.ResultNotFqdn { + if checker.IsFqdn("abcd") == nil { t.Fail() } } func TestCheckFdqnShortTld(t *testing.T) { - if checker.IsFqdn("abcd.c") != checker.ResultNotFqdn { + if checker.IsFqdn("abcd.c") == nil { t.Fail() } } func TestCheckFdqnNumericTld(t *testing.T) { - if checker.IsFqdn("abcd.1234") != checker.ResultNotFqdn { + if checker.IsFqdn("abcd.1234") == nil { t.Fail() } } func TestCheckFdqnLong(t *testing.T) { - if checker.IsFqdn("abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.com") != checker.ResultNotFqdn { + if checker.IsFqdn("abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd.com") == nil { t.Fail() } } func TestCheckFdqnInvalidCharacters(t *testing.T) { - if checker.IsFqdn("ab_cd.com") != checker.ResultNotFqdn { + if checker.IsFqdn("ab_cd.com") == nil { t.Fail() } } func TestCheckFdqnStaringWithHyphen(t *testing.T) { - if checker.IsFqdn("-abcd.com") != checker.ResultNotFqdn { + if checker.IsFqdn("-abcd.com") == nil { t.Fail() } } func TestCheckFdqnStaringEndingWithHyphen(t *testing.T) { - if checker.IsFqdn("abcd-.com") != checker.ResultNotFqdn { + if checker.IsFqdn("abcd-.com") == nil { t.Fail() } } func TestCheckFdqnStartingWithDot(t *testing.T) { - if checker.IsFqdn(".abcd.com") != checker.ResultNotFqdn { + if checker.IsFqdn(".abcd.com") == nil { t.Fail() } } func TestCheckFdqnEndingWithDot(t *testing.T) { - if checker.IsFqdn("abcd.com.") != checker.ResultNotFqdn { + if checker.IsFqdn("abcd.com.") == nil { t.Fail() } } diff --git a/html_escape.go b/html_escape.go index 2701f56..012448d 100644 --- a/html_escape.go +++ b/html_escape.go @@ -20,12 +20,12 @@ func makeHTMLEscape(_ string) CheckFunc { // normalizeHTMLEscape applies HTML escaping to special characters. // Uses html.EscapeString for the actual escape operation. -func normalizeHTMLEscape(value, _ reflect.Value) Result { +func normalizeHTMLEscape(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(html.EscapeString(value.String())) - return ResultValid + return nil } diff --git a/html_escape_test.go b/html_escape_test.go index 799eba4..f823afc 100644 --- a/html_escape_test.go +++ b/html_escape_test.go @@ -13,7 +13,6 @@ import ( func TestNormalizeHTMLEscapeNonString(t *testing.T) { defer checker.FailIfNoPanic(t) - type Comment struct { Body int `checkers:"html-escape"` } diff --git a/html_unescape.go b/html_unescape.go index f202ae1..3c8a93f 100644 --- a/html_unescape.go +++ b/html_unescape.go @@ -20,12 +20,12 @@ func makeHTMLUnescape(_ string) CheckFunc { // normalizeHTMLUnescape applies HTML unescaping to special characters. // Uses html.UnescapeString for the actual unescape operation. -func normalizeHTMLUnescape(value, _ reflect.Value) Result { +func normalizeHTMLUnescape(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(html.UnescapeString(value.String())) - return ResultValid + return nil } diff --git a/ip.go b/ip.go index a113269..9fa240b 100644 --- a/ip.go +++ b/ip.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "net" "reflect" ) @@ -13,17 +14,17 @@ import ( // CheckerIP is the name of the checker. const CheckerIP = "ip" -// ResultNotIP indicates that the given value is not an IP address. -const ResultNotIP = "NOT_IP" +// ErrNotIP indicates that the given value is not an IP address. +var ErrNotIP = errors.New("please enter a valid IP address") // IsIP checks if the given value is an IP address. -func IsIP(value string) Result { +func IsIP(value string) error { ip := net.ParseIP(value) if ip == nil { - return ResultNotIP + return ErrNotIP } - return ResultValid + return nil } // makeIP makes a checker function for the ip checker. @@ -32,7 +33,7 @@ func makeIP(_ string) CheckFunc { } // checkIP checks if the given value is an IP address. -func checkIP(value, _ reflect.Value) Result { +func checkIP(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/ip_test.go b/ip_test.go index a09bc28..4995d8f 100644 --- a/ip_test.go +++ b/ip_test.go @@ -12,21 +12,20 @@ import ( ) func ExampleIsIP() { - result := checker.IsIP("2001:db8::68") - - if result != checker.ResultValid { + err := checker.IsIP("2001:db8::68") + if err != nil { // Send the mistakes back to the user } } func TestIsIPInvalid(t *testing.T) { - if checker.IsIP("900.800.200.100") == checker.ResultValid { + if checker.IsIP("900.800.200.100") == nil { t.Fail() } } func TestIsIPValid(t *testing.T) { - if checker.IsIP("2001:db8::68") != checker.ResultValid { + if checker.IsIP("2001:db8::68") != nil { t.Fail() } } diff --git a/ipv4.go b/ipv4.go index 68225fc..93d28ca 100644 --- a/ipv4.go +++ b/ipv4.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "net" "reflect" ) @@ -13,21 +14,21 @@ import ( // CheckerIPV4 is the name of the checker. const CheckerIPV4 = "ipv4" -// ResultNotIPV4 indicates that the given value is not an IPv4 address. -const ResultNotIPV4 = "NOT_IP_V4" +// ErrNotIPV4 indicates that the given value is not an IPv4 address. +var ErrNotIPV4 = errors.New("please enter a valid IPv4 address") // IsIPV4 checks if the given value is an IPv4 address. -func IsIPV4(value string) Result { +func IsIPV4(value string) error { ip := net.ParseIP(value) if ip == nil { - return ResultNotIPV4 + return ErrNotIPV4 } if ip.To4() == nil { - return ResultNotIPV4 + return ErrNotIPV4 } - return ResultValid + return nil } // makeIPV4 makes a checker function for the ipV4 checker. @@ -36,7 +37,7 @@ func makeIPV4(_ string) CheckFunc { } // checkIPV4 checks if the given value is an IPv4 address. -func checkIPV4(value, _ reflect.Value) Result { +func checkIPV4(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/ipv4_test.go b/ipv4_test.go index f38f542..fba513d 100644 --- a/ipv4_test.go +++ b/ipv4_test.go @@ -12,27 +12,26 @@ import ( ) func ExampleIsIPV4() { - result := checker.IsIPV4("192.168.1.1") - - if result != checker.ResultValid { + err := checker.IsIPV4("192.168.1.1") + if err != nil { // Send the mistakes back to the user } } func TestIsIPV4Invalid(t *testing.T) { - if checker.IsIPV4("900.800.200.100") == checker.ResultValid { + if checker.IsIPV4("900.800.200.100") == nil { t.Fail() } } func TestIsIPV4InvalidV6(t *testing.T) { - if checker.IsIPV4("2001:db8::68") == checker.ResultValid { + if checker.IsIPV4("2001:db8::68") == nil { t.Fail() } } func TestIsIPV4Valid(t *testing.T) { - if checker.IsIPV4("192.168.1.1") != checker.ResultValid { + if checker.IsIPV4("192.168.1.1") != nil { t.Fail() } } diff --git a/ipv6.go b/ipv6.go index da6ba34..8fe9a07 100644 --- a/ipv6.go +++ b/ipv6.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "net" "reflect" ) @@ -13,21 +14,21 @@ import ( // CheckerIPV6 is the name of the checker. const CheckerIPV6 = "ipv6" -// ResultNotIPV6 indicates that the given value is not an IPv6 address. -const ResultNotIPV6 = "NOT_IP_V6" +// ErrNotIPV6 indicates that the given value is not an IPv6 address. +var ErrNotIPV6 = errors.New("please enter a valid IPv6 address") // IsIPV6 checks if the given value is an IPv6 address. -func IsIPV6(value string) Result { +func IsIPV6(value string) error { ip := net.ParseIP(value) if ip == nil { - return ResultNotIPV6 + return ErrNotIPV6 } if ip.To4() != nil { - return ResultNotIPV6 + return ErrNotIPV6 } - return ResultValid + return nil } // makeIPV6 makes a checker function for the ipV6 checker. @@ -36,7 +37,7 @@ func makeIPV6(_ string) CheckFunc { } // checkIPV6 checks if the given value is an IPv6 address. -func checkIPV6(value, _ reflect.Value) Result { +func checkIPV6(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/ipv6_test.go b/ipv6_test.go index 68d9e95..c8d8d4e 100644 --- a/ipv6_test.go +++ b/ipv6_test.go @@ -12,27 +12,27 @@ import ( ) func ExampleIsIPV6() { - result := checker.IsIPV6("2001:db8::68") + err := checker.IsIPV6("2001:db8::68") - if result != checker.ResultValid { + if err != nil { // Send the mistakes back to the user } } func TestIsIPV6Invalid(t *testing.T) { - if checker.IsIPV6("900.800.200.100") == checker.ResultValid { + if checker.IsIPV6("900.800.200.100") == nil { t.Fail() } } func TestIsIPV6InvalidV4(t *testing.T) { - if checker.IsIPV6("192.168.1.1") == checker.ResultValid { + if checker.IsIPV6("192.168.1.1") == nil { t.Fail() } } func TestIsIPV6Valid(t *testing.T) { - if checker.IsIPV6("2001:db8::68") != checker.ResultValid { + if checker.IsIPV6("2001:db8::68") != nil { t.Fail() } } diff --git a/isbn.go b/isbn.go index 3b4d4d6..67fbb10 100644 --- a/isbn.go +++ b/isbn.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "strings" ) @@ -19,15 +20,15 @@ import ( // CheckerISBN is the name of the checker. const CheckerISBN = "isbn" -// ResultNotISBN indicates that the given value is not a valid ISBN. -const ResultNotISBN = "NOT_ISBN" +// ErrNotISBN indicates that the given value is not a valid ISBN. +var ErrNotISBN = errors.New("please enter a valid ISBN number") // IsISBN10 checks if the given value is a valid ISBN-10 number. -func IsISBN10(value string) Result { +func IsISBN10(value string) error { value = strings.ReplaceAll(value, "-", "") if len(value) != 10 { - return ResultNotISBN + return ErrNotISBN } digits := []rune(value) @@ -39,18 +40,18 @@ func IsISBN10(value string) Result { } if sum%11 != 0 { - return ResultNotISBN + return ErrNotISBN } - return ResultValid + return nil } // IsISBN13 checks if the given value is a valid ISBN-13 number. -func IsISBN13(value string) Result { +func IsISBN13(value string) error { value = strings.ReplaceAll(value, "-", "") if len(value) != 13 { - return ResultNotISBN + return ErrNotISBN } digits := []rune(value) @@ -66,14 +67,14 @@ func IsISBN13(value string) Result { } if sum%10 != 0 { - return ResultNotISBN + return ErrNotISBN } - return ResultValid + return nil } // IsISBN checks if the given value is a valid ISBN number. -func IsISBN(value string) Result { +func IsISBN(value string) error { value = strings.ReplaceAll(value, "-", "") if len(value) == 10 { @@ -82,7 +83,7 @@ func IsISBN(value string) Result { return IsISBN13(value) } - return ResultNotISBN + return ErrNotISBN } // isbnDigitToInt returns the integer value of given ISBN digit. @@ -100,13 +101,13 @@ func makeISBN(config string) CheckFunc { panic("invalid format") } - return func(value, parent reflect.Value) Result { + return func(value, parent reflect.Value) error { return checkISBN(value, parent, config) } } // checkISBN checks if the given value is a valid ISBN number. -func checkISBN(value, _ reflect.Value, mode string) Result { +func checkISBN(value, _ reflect.Value, mode string) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/isbn_test.go b/isbn_test.go index d8fe4be..f173981 100644 --- a/isbn_test.go +++ b/isbn_test.go @@ -6,112 +6,113 @@ package checker_test import ( + "errors" "testing" "github.com/cinar/checker" ) func ExampleIsISBN10() { - result := checker.IsISBN10("1430248270") - if result != checker.ResultValid { + err := checker.IsISBN10("1430248270") + if err != nil { // Send the mistakes back to the user } } func TestIsISBN10Valid(t *testing.T) { - result := checker.IsISBN10("1430248270") - if result != checker.ResultValid { + err := checker.IsISBN10("1430248270") + if err != nil { t.Fail() } } func TestIsISBN10ValidX(t *testing.T) { - result := checker.IsISBN10("007462542X") - if result != checker.ResultValid { + err := checker.IsISBN10("007462542X") + if err != nil { t.Fail() } } func TestIsISBN10ValidWithDashes(t *testing.T) { - result := checker.IsISBN10("1-4302-4827-0") - if result != checker.ResultValid { + err := checker.IsISBN10("1-4302-4827-0") + if err != nil { t.Fail() } } func TestIsISBN10InvalidLength(t *testing.T) { - result := checker.IsISBN10("143024827") - if result != checker.ResultNotISBN { + err := checker.IsISBN10("143024827") + if !errors.Is(err, checker.ErrNotISBN) { t.Fail() } } func TestIsISBN10InvalidCheck(t *testing.T) { - result := checker.IsISBN10("1430248272") - if result != checker.ResultNotISBN { + err := checker.IsISBN10("1430248272") + if !errors.Is(err, checker.ErrNotISBN) { t.Fail() } } func ExampleIsISBN13() { - result := checker.IsISBN13("9781430248279") - if result != checker.ResultValid { + err := checker.IsISBN13("9781430248279") + if err != nil { // Send the mistakes back to the user } } func TestIsISBN13Valid(t *testing.T) { - result := checker.IsISBN13("9781430248279") - if result != checker.ResultValid { + err := checker.IsISBN13("9781430248279") + if err != nil { t.Fail() } } func TestIsISBN13ValidWithDashes(t *testing.T) { - result := checker.IsISBN13("978-1-4302-4827-9") - if result != checker.ResultValid { + err := checker.IsISBN13("978-1-4302-4827-9") + if err != nil { t.Fail() } } func TestIsISBN13InvalidLength(t *testing.T) { - result := checker.IsISBN13("978143024827") - if result != checker.ResultNotISBN { + err := checker.IsISBN13("978143024827") + if !errors.Is(err, checker.ErrNotISBN) { t.Fail() } } func TestIsISBN13InvalidCheck(t *testing.T) { - result := checker.IsISBN13("9781430248272") - if result != checker.ResultNotISBN { + err := checker.IsISBN13("9781430248272") + if !errors.Is(err, checker.ErrNotISBN) { t.Fail() } } func ExampleIsISBN() { - result := checker.IsISBN("1430248270") - if result != checker.ResultValid { + err := checker.IsISBN("1430248270") + if err != nil { // Send the mistakes back to the user } } func TestIsISBNValid10(t *testing.T) { - result := checker.IsISBN("1430248270") - if result != checker.ResultValid { + err := checker.IsISBN("1430248270") + if err != nil { t.Fail() } } func TestIsISBNValid13(t *testing.T) { - result := checker.IsISBN("9781430248279") - if result != checker.ResultValid { + err := checker.IsISBN("9781430248279") + if err != nil { t.Fail() } } func TestIsISBNInvalidLenght(t *testing.T) { - result := checker.IsISBN("978143024827") - if result != checker.ResultNotISBN { + err := checker.IsISBN("978143024827") + if err != checker.ErrNotISBN { t.Fail() } } diff --git a/lower.go b/lower.go index 6cf6987..3843c33 100644 --- a/lower.go +++ b/lower.go @@ -19,12 +19,12 @@ func makeLower(_ string) CheckFunc { } // normalizeLower maps all Unicode letters in the given value to their lower case. -func normalizeLower(value, _ reflect.Value) Result { +func normalizeLower(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(strings.ToLower(value.String())) - return ResultValid + return nil } diff --git a/lower_test.go b/lower_test.go index e5f660c..112fbd8 100644 --- a/lower_test.go +++ b/lower_test.go @@ -23,7 +23,7 @@ func TestNormalizeLowerNonString(t *testing.T) { checker.Check(user) } -func TestNormalizeLowerResultValid(t *testing.T) { +func TestNormalizeLowerErrValid(t *testing.T) { type User struct { Username string `checkers:"lower"` } diff --git a/luhn.go b/luhn.go index 4f8808a..6e222d3 100644 --- a/luhn.go +++ b/luhn.go @@ -6,28 +6,29 @@ package checker import ( + "errors" "reflect" ) // CheckerLuhn is the name of the checker. const CheckerLuhn = "luhn" -// ResultNotLuhn indicates that the given number is not valid based on the Luhn algorithm. -const ResultNotLuhn = "NOT_LUHN" +// ErrNotLuhn indicates that the given number is not valid based on the Luhn algorithm. +var ErrNotLuhn = errors.New("please enter a valid LUHN") // doubleTable is the values for the last digits of doubled digits added. var doubleTable = [10]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9} // IsLuhn checks if the given number is valid based on the Luhn algorithm. -func IsLuhn(number string) Result { +func IsLuhn(number string) error { digits := number[:len(number)-1] check := rune(number[len(number)-1]) if calculateLuhnCheckDigit(digits) != check { - return ResultNotLuhn + return ErrNotLuhn } - return ResultValid + return nil } // makeLuhn makes a checker function for the Luhn algorithm. @@ -36,7 +37,7 @@ func makeLuhn(_ string) CheckFunc { } // checkLuhn checks if the given number is valid based on the Luhn algorithm. -func checkLuhn(value, _ reflect.Value) Result { +func checkLuhn(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/luhn_test.go b/luhn_test.go index bdd06a5..e193621 100644 --- a/luhn_test.go +++ b/luhn_test.go @@ -12,9 +12,8 @@ import ( ) func ExampleIsLuhn() { - result := checker.IsLuhn("4012888888881881") - - if result != checker.ResultValid { + err := checker.IsLuhn("4012888888881881") + if err != nil { // Send the mistakes back to the user } } @@ -28,7 +27,7 @@ func TestIsLuhnValid(t *testing.T) { } for _, number := range numbers { - if checker.IsLuhn(number) != checker.ResultValid { + if checker.IsLuhn(number) != nil { t.Fail() } } diff --git a/mac.go b/mac.go index 7c6fbf2..509ecc3 100644 --- a/mac.go +++ b/mac.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "net" "reflect" ) @@ -13,17 +14,17 @@ import ( // CheckerMac is the name of the checker. const CheckerMac = "mac" -// ResultNotMac indicates that the given value is not an MAC address. -const ResultNotMac = "NOT_MAC" +// ErrNotMac indicates that the given value is not an MAC address. +var ErrNotMac = errors.New("please enter a valid MAC address") // IsMac checks if the given value is a valid an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet IP over InfiniBand link-layer address. -func IsMac(value string) Result { +func IsMac(value string) error { _, err := net.ParseMAC(value) if err != nil { - return ResultNotMac + return ErrNotMac } - return ResultValid + return nil } // makeMac makes a checker function for the ip checker. @@ -32,7 +33,7 @@ func makeMac(_ string) CheckFunc { } // checkMac checks if the given value is a valid an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet IP over InfiniBand link-layer address. -func checkMac(value, _ reflect.Value) Result { +func checkMac(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/mac_test.go b/mac_test.go index 79f9729..e966765 100644 --- a/mac_test.go +++ b/mac_test.go @@ -12,21 +12,20 @@ import ( ) func ExampleIsMac() { - result := checker.IsMac("00:00:5e:00:53:01") - - if result != checker.ResultValid { + err := checker.IsMac("00:00:5e:00:53:01") + if err != nil { // Send the mistakes back to the user } } func TestIsMacInvalid(t *testing.T) { - if checker.IsMac("1234") == checker.ResultValid { + if checker.IsMac("1234") == nil { t.Fail() } } func TestIsMacValid(t *testing.T) { - if checker.IsMac("00:00:5e:00:53:01") != checker.ResultValid { + if checker.IsMac("00:00:5e:00:53:01") != nil { t.Fail() } } diff --git a/max.go b/max.go index 04a028e..ed8c2d3 100644 --- a/max.go +++ b/max.go @@ -6,6 +6,7 @@ package checker import ( + "fmt" "reflect" "strconv" ) @@ -13,11 +14,8 @@ import ( // CheckerMax is the name of the checker. const CheckerMax = "max" -// ResultNotMax indicates that the given value is above the defined maximum. -const ResultNotMax = "NOT_MIN" - // IsMax checks if the given value is below than the given maximum. -func IsMax(value interface{}, max float64) Result { +func IsMax(value interface{}, max float64) error { return checkMax(reflect.Indirect(reflect.ValueOf(value)), reflect.ValueOf(nil), max) } @@ -28,18 +26,18 @@ func makeMax(config string) CheckFunc { panic("unable to parse max") } - return func(value, parent reflect.Value) Result { + return func(value, parent reflect.Value) error { return checkMax(value, parent, max) } } // checkMax checks if the given value is less than the given maximum. -func checkMax(value, _ reflect.Value, max float64) Result { +func checkMax(value, _ reflect.Value, max float64) error { n := numberOf(value) if n > max { - return ResultNotMax + return fmt.Errorf("please enter a number less than %g", max) } - return ResultValid + return nil } diff --git a/max_test.go b/max_test.go index 144246f..c6f3adf 100644 --- a/max_test.go +++ b/max_test.go @@ -14,9 +14,8 @@ import ( func ExampleIsMax() { quantity := 5 - result := checker.IsMax(quantity, 10) - - if result != checker.ResultValid { + err := checker.IsMax(quantity, 10) + if err != nil { // Send the mistakes back to the user } } @@ -24,7 +23,7 @@ func ExampleIsMax() { func TestIsMaxValid(t *testing.T) { n := 5 - if checker.IsMax(n, 10) != checker.ResultValid { + if checker.IsMax(n, 10) != nil { t.Fail() } } diff --git a/maxlength.go b/maxlength.go index 910e9f4..63a0f0a 100644 --- a/maxlength.go +++ b/maxlength.go @@ -6,6 +6,7 @@ package checker import ( + "fmt" "reflect" "strconv" ) @@ -13,11 +14,8 @@ import ( // CheckerMaxLength is the name of the checker. const CheckerMaxLength = "max-length" -// ResultNotMaxLength indicates that the length of the given value is above the defined number. -const ResultNotMaxLength = "NOT_MAX_LENGTH" - // IsMaxLength checks if the length of the given value is less than the given maximum length. -func IsMaxLength(value interface{}, maxLength int) Result { +func IsMaxLength(value interface{}, maxLength int) error { return checkMaxLength(reflect.Indirect(reflect.ValueOf(value)), reflect.ValueOf(nil), maxLength) } @@ -28,17 +26,17 @@ func makeMaxLength(config string) CheckFunc { panic("unable to parse max length value") } - return func(value, parent reflect.Value) Result { + return func(value, parent reflect.Value) error { return checkMaxLength(value, parent, maxLength) } } // checkMaxLength checks if the length of the given value is less than the given maximum length. // The function uses the reflect.Value.Len() function to determaxe the length of the value. -func checkMaxLength(value, _ reflect.Value, maxLength int) Result { +func checkMaxLength(value, _ reflect.Value, maxLength int) error { if value.Len() > maxLength { - return ResultNotMaxLength + return fmt.Errorf("please enter %d characters or less", maxLength-1) } - return ResultValid + return nil } diff --git a/maxlength_test.go b/maxlength_test.go index 5322cfc..e2e6d3b 100644 --- a/maxlength_test.go +++ b/maxlength_test.go @@ -14,9 +14,8 @@ import ( func ExampleIsMaxLength() { s := "1234" - result := checker.IsMaxLength(s, 4) - - if result != checker.ResultValid { + err := checker.IsMaxLength(s, 4) + if err != nil { // Send the mistakes back to the user } } @@ -24,7 +23,7 @@ func ExampleIsMaxLength() { func TestIsMaxLengthValid(t *testing.T) { s := "1234" - if checker.IsMaxLength(s, 4) != checker.ResultValid { + if checker.IsMaxLength(s, 4) != nil { t.Fail() } } diff --git a/min.go b/min.go index dcab579..1807b1f 100644 --- a/min.go +++ b/min.go @@ -6,6 +6,7 @@ package checker import ( + "fmt" "reflect" "strconv" ) @@ -13,11 +14,8 @@ import ( // CheckerMin is the name of the checker. const CheckerMin = "min" -// ResultNotMin indicates that the given value is below the defined minimum. -const ResultNotMin = "NOT_MIN" - // IsMin checks if the given value is above than the given minimum. -func IsMin(value interface{}, min float64) Result { +func IsMin(value interface{}, min float64) error { return checkMin(reflect.Indirect(reflect.ValueOf(value)), reflect.ValueOf(nil), min) } @@ -28,18 +26,18 @@ func makeMin(config string) CheckFunc { panic("unable to parse min") } - return func(value, parent reflect.Value) Result { + return func(value, parent reflect.Value) error { return checkMin(value, parent, min) } } // checkMin checks if the given value is greather than the given minimum. -func checkMin(value, _ reflect.Value, min float64) Result { +func checkMin(value, _ reflect.Value, min float64) error { n := numberOf(value) if n < min { - return ResultNotMin + return fmt.Errorf("please enter a number less than %g", min) } - return ResultValid + return nil } diff --git a/min_test.go b/min_test.go index b518e3c..40efbe7 100644 --- a/min_test.go +++ b/min_test.go @@ -14,9 +14,8 @@ import ( func ExampleIsMin() { age := 45 - result := checker.IsMin(age, 21) - - if result != checker.ResultValid { + err := checker.IsMin(age, 21) + if err != nil { // Send the mistakes back to the user } } @@ -24,7 +23,7 @@ func ExampleIsMin() { func TestIsMinValid(t *testing.T) { n := 45 - if checker.IsMin(n, 21) != checker.ResultValid { + if checker.IsMin(n, 21) != nil { t.Fail() } } diff --git a/minlenght.go b/minlenght.go index 376444d..b8bf0e1 100644 --- a/minlenght.go +++ b/minlenght.go @@ -6,6 +6,7 @@ package checker import ( + "fmt" "reflect" "strconv" ) @@ -13,11 +14,8 @@ import ( // CheckerMinLength is the name of the checker. const CheckerMinLength = "min-length" -// ResultNotMinLength indicates that the length of the given value is below the defined number. -const ResultNotMinLength = "NOT_MIN_LENGTH" - // IsMinLength checks if the length of the given value is greather than the given minimum length. -func IsMinLength(value interface{}, minLength int) Result { +func IsMinLength(value interface{}, minLength int) error { return checkMinLength(reflect.Indirect(reflect.ValueOf(value)), reflect.ValueOf(nil), minLength) } @@ -28,17 +26,17 @@ func makeMinLength(config string) CheckFunc { panic("unable to parse min length value") } - return func(value, parent reflect.Value) Result { + return func(value, parent reflect.Value) error { return checkMinLength(value, parent, minLength) } } // checkMinLength checks if the length of the given value is greather than the given minimum length. // The function uses the reflect.Value.Len() function to determine the length of the value. -func checkMinLength(value, _ reflect.Value, minLength int) Result { +func checkMinLength(value, _ reflect.Value, minLength int) error { if value.Len() < minLength { - return ResultNotMinLength + return fmt.Errorf("please enter at least %d characters", minLength) } - return ResultValid + return nil } diff --git a/minlength_test.go b/minlength_test.go index 2a95559..045e958 100644 --- a/minlength_test.go +++ b/minlength_test.go @@ -14,9 +14,8 @@ import ( func ExampleIsMinLength() { s := "1234" - result := checker.IsMinLength(s, 4) - - if result != checker.ResultValid { + err := checker.IsMinLength(s, 4) + if err != nil { // Send the mistakes back to the user } } @@ -24,7 +23,7 @@ func ExampleIsMinLength() { func TestIsMinLengthValid(t *testing.T) { s := "1234" - if checker.IsMinLength(s, 4) != checker.ResultValid { + if checker.IsMinLength(s, 4) != nil { t.Fail() } } diff --git a/regexp.go b/regexp.go index f4e24ab..b48ff18 100644 --- a/regexp.go +++ b/regexp.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "reflect" "regexp" ) @@ -13,39 +14,39 @@ import ( // CheckerRegexp is the name of the checker. const CheckerRegexp = "regexp" -// ResultNotMatch indicates that the given string does not match the regexp pattern. -const ResultNotMatch = "NOT_MATCH" +// ErrNotMatch indicates that the given string does not match the regexp pattern. +var ErrNotMatch = errors.New("please enter a valid input") // MakeRegexpMaker makes a regexp checker maker for the given regexp expression with the given invalid result. -func MakeRegexpMaker(expression string, invalidResult Result) MakeFunc { +func MakeRegexpMaker(expression string, invalidError error) MakeFunc { return func(_ string) CheckFunc { - return MakeRegexpChecker(expression, invalidResult) + return MakeRegexpChecker(expression, invalidError) } } // MakeRegexpChecker makes a regexp checker for the given regexp expression with the given invalid result. -func MakeRegexpChecker(expression string, invalidResult Result) CheckFunc { +func MakeRegexpChecker(expression string, invalidError error) CheckFunc { pattern := regexp.MustCompile(expression) - return func(value, parent reflect.Value) Result { - return checkRegexp(value, pattern, invalidResult) + return func(value, parent reflect.Value) error { + return checkRegexp(value, pattern, invalidError) } } // makeRegexp makes a checker function for the regexp. func makeRegexp(config string) CheckFunc { - return MakeRegexpChecker(config, ResultNotMatch) + return MakeRegexpChecker(config, ErrNotMatch) } // checkRegexp checks if the given string matches the regexp pattern. -func checkRegexp(value reflect.Value, pattern *regexp.Regexp, invalidResult Result) Result { +func checkRegexp(value reflect.Value, pattern *regexp.Regexp, invalidError error) error { if value.Kind() != reflect.String { panic("string expected") } if !pattern.MatchString(value.String()) { - return invalidResult + return invalidError } - return ResultValid + return nil } diff --git a/regexp_test.go b/regexp_test.go index 64a443a..58fa217 100644 --- a/regexp_test.go +++ b/regexp_test.go @@ -6,6 +6,7 @@ package checker_test import ( + "errors" "reflect" "testing" @@ -55,16 +56,16 @@ func TestCheckRegexpValid(t *testing.T) { } func TestMakeRegexpChecker(t *testing.T) { - checkHex := checker.MakeRegexpChecker("^[A-Fa-f0-9]+$", "NOT_HEX") + checkHex := checker.MakeRegexpChecker("^[A-Fa-f0-9]+$", errors.New("Not Hex")) - result := checkHex(reflect.ValueOf("f0f0f0"), reflect.ValueOf(nil)) - if result != checker.ResultValid { + err := checkHex(reflect.ValueOf("f0f0f0"), reflect.ValueOf(nil)) + if err != nil { t.Fail() } } func TestMakeRegexpMaker(t *testing.T) { - checker.Register("hex", checker.MakeRegexpMaker("^[A-Fa-f0-9]+$", "NOT_HEX")) + checker.Register("hex", checker.MakeRegexpMaker("^[A-Fa-f0-9]+$", errors.New("Not Hex"))) type Theme struct { Color string `checkers:"hex"` diff --git a/required.go b/required.go index bfc8c48..16c092e 100644 --- a/required.go +++ b/required.go @@ -5,16 +5,19 @@ package checker -import "reflect" +import ( + "errors" + "reflect" +) // CheckerRequired is the name of the checker. const CheckerRequired = "required" -// ResultRequired indicates that the required value is missing. -const ResultRequired Result = "REQUIRED" +// ErrRequired indicates that the required value is missing. +var ErrRequired = errors.New("is required") // IsRequired checks if the given required value is present. -func IsRequired(v interface{}) Result { +func IsRequired(v interface{}) error { return checkRequired(reflect.ValueOf(v), reflect.ValueOf(nil)) } @@ -24,16 +27,16 @@ func makeRequired(_ string) CheckFunc { } // checkRequired checks if the required value is present. -func checkRequired(value, _ reflect.Value) Result { +func checkRequired(value, _ reflect.Value) error { if value.IsZero() { - return ResultRequired + return ErrRequired } k := value.Kind() if (k == reflect.Array || k == reflect.Map || k == reflect.Slice) && value.Len() == 0 { - return ResultRequired + return ErrRequired } - return ResultValid + return nil } diff --git a/required_test.go b/required_test.go index 27a43cc..958aff9 100644 --- a/required_test.go +++ b/required_test.go @@ -14,16 +14,16 @@ import ( func ExampleIsRequired() { var name string - result := checker.IsRequired(name) - if result != checker.ResultValid { - // Send the result back to the user + err := checker.IsRequired(name) + if err != nil { + // Send the err back to the user } } func TestIsRequired(t *testing.T) { s := "valid" - if checker.IsRequired(s) != checker.ResultValid { + if checker.IsRequired(s) != nil { t.Fail() } } @@ -31,7 +31,7 @@ func TestIsRequired(t *testing.T) { func TestIsRequiredUninitializedString(t *testing.T) { var s string - if checker.IsRequired(s) != checker.ResultRequired { + if checker.IsRequired(s) != checker.ErrRequired { t.Fail() } } @@ -39,7 +39,7 @@ func TestIsRequiredUninitializedString(t *testing.T) { func TestIsRequiredEmptyString(t *testing.T) { s := "" - if checker.IsRequired(s) == checker.ResultValid { + if checker.IsRequired(s) == nil { t.Fail() } } @@ -47,7 +47,7 @@ func TestIsRequiredEmptyString(t *testing.T) { func TestIsRequiredUninitializedNumber(t *testing.T) { var n int - if checker.IsRequired(n) != checker.ResultRequired { + if checker.IsRequired(n) != checker.ErrRequired { t.Fail() } } @@ -55,7 +55,7 @@ func TestIsRequiredUninitializedNumber(t *testing.T) { func TestIsRequiredValidSlice(t *testing.T) { s := []int{1} - if checker.IsRequired(s) != checker.ResultValid { + if checker.IsRequired(s) != nil { t.Fail() } } @@ -63,7 +63,7 @@ func TestIsRequiredValidSlice(t *testing.T) { func TestIsRequiredUninitializedSlice(t *testing.T) { var s []int - if checker.IsRequired(s) != checker.ResultRequired { + if checker.IsRequired(s) != checker.ErrRequired { t.Fail() } } @@ -71,7 +71,7 @@ func TestIsRequiredUninitializedSlice(t *testing.T) { func TestIsRequiredEmptySlice(t *testing.T) { s := make([]int, 0) - if checker.IsRequired(s) != checker.ResultRequired { + if checker.IsRequired(s) != checker.ErrRequired { t.Fail() } } @@ -79,7 +79,7 @@ func TestIsRequiredEmptySlice(t *testing.T) { func TestIsRequiredValidArray(t *testing.T) { s := [1]int{1} - if checker.IsRequired(s) != checker.ResultValid { + if checker.IsRequired(s) != nil { t.Fail() } } @@ -87,7 +87,7 @@ func TestIsRequiredValidArray(t *testing.T) { func TestIsRequiredEmptyArray(t *testing.T) { s := [1]int{} - if checker.IsRequired(s) != checker.ResultRequired { + if checker.IsRequired(s) != checker.ErrRequired { t.Fail() } } @@ -97,7 +97,7 @@ func TestIsRequiredValidMap(t *testing.T) { "a": "b", } - if checker.IsRequired(m) != checker.ResultValid { + if checker.IsRequired(m) != nil { t.Fail() } } @@ -105,7 +105,7 @@ func TestIsRequiredValidMap(t *testing.T) { func TestIsRequiredUninitializedMap(t *testing.T) { var m map[string]string - if checker.IsRequired(m) != checker.ResultRequired { + if checker.IsRequired(m) != checker.ErrRequired { t.Fail() } } @@ -113,7 +113,7 @@ func TestIsRequiredUninitializedMap(t *testing.T) { func TestCheckRequiredEmptyMap(t *testing.T) { m := map[string]string{} - if checker.IsRequired(m) != checker.ResultRequired { + if checker.IsRequired(m) != checker.ErrRequired { t.Fail() } } diff --git a/same.go b/same.go index 1901041..10b67d2 100644 --- a/same.go +++ b/same.go @@ -6,24 +6,25 @@ package checker import ( + "errors" "reflect" ) // CheckerSame is the name of the checker. const CheckerSame = "same" -// ResultNotSame indicates that the given two values are not equal to each other. -const ResultNotSame = "NOT_SAME" +// ErrNotSame indicates that the given two values are not equal to each other. +var ErrNotSame = errors.New("does not match the other") // makeSame makes a checker function for the same checker. func makeSame(config string) CheckFunc { - return func(value, parent reflect.Value) Result { + return func(value, parent reflect.Value) error { return checkSame(value, parent, config) } } // checkSame checks if the given value is equal to the value of the field with the given name. -func checkSame(value, parent reflect.Value, name string) Result { +func checkSame(value, parent reflect.Value, name string) error { other := parent.FieldByName(name) if !other.IsValid() { @@ -33,8 +34,8 @@ func checkSame(value, parent reflect.Value, name string) Result { other = reflect.Indirect(other) if !value.Equal(other) { - return ResultNotSame + return ErrNotSame } - return ResultValid + return nil } diff --git a/title.go b/title.go index 9a75bac..90d2b6b 100644 --- a/title.go +++ b/title.go @@ -20,7 +20,7 @@ func makeTitle(_ string) CheckFunc { } // normalizeTitle maps the first letter of each word to their upper case. -func normalizeTitle(value, _ reflect.Value) Result { +func normalizeTitle(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } @@ -45,5 +45,5 @@ func normalizeTitle(value, _ reflect.Value) Result { value.SetString(sb.String()) - return ResultValid + return nil } diff --git a/title_test.go b/title_test.go index 2a56175..bf6900c 100644 --- a/title_test.go +++ b/title_test.go @@ -23,7 +23,7 @@ func TestNormalizeTitleNonString(t *testing.T) { checker.Check(book) } -func TestNormalizeTitleResultValid(t *testing.T) { +func TestNormalizeTitleErrValid(t *testing.T) { type Book struct { Chapter string `checkers:"title"` } diff --git a/trim.go b/trim.go index 36638be..88cbc82 100644 --- a/trim.go +++ b/trim.go @@ -19,12 +19,12 @@ func makeTrim(_ string) CheckFunc { } // normalizeTrim removes the whitespaces at the beginning and at the end of the given value. -func normalizeTrim(value, _ reflect.Value) Result { +func normalizeTrim(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(strings.Trim(value.String(), " \t")) - return ResultValid + return nil } diff --git a/trim_left.go b/trim_left.go index a0aee1a..e3e53ba 100644 --- a/trim_left.go +++ b/trim_left.go @@ -19,12 +19,12 @@ func makeTrimLeft(_ string) CheckFunc { } // normalizeTrim removes the whitespaces at the beginning of the given value. -func normalizeTrimLeft(value, _ reflect.Value) Result { +func normalizeTrimLeft(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(strings.TrimLeft(value.String(), " \t")) - return ResultValid + return nil } diff --git a/trim_left_test.go b/trim_left_test.go index bd21696..2f93471 100644 --- a/trim_left_test.go +++ b/trim_left_test.go @@ -23,7 +23,7 @@ func TestNormalizeTrimLeftNonString(t *testing.T) { checker.Check(user) } -func TestNormalizeTrimLeftResultValid(t *testing.T) { +func TestNormalizeTrimLeftErrValid(t *testing.T) { type User struct { Username string `checkers:"trim-left"` } diff --git a/trim_right.go b/trim_right.go index 2790c44..82d4115 100644 --- a/trim_right.go +++ b/trim_right.go @@ -19,12 +19,12 @@ func makeTrimRight(_ string) CheckFunc { } // normalizeTrimRight removes the whitespaces at the end of the given value. -func normalizeTrimRight(value, _ reflect.Value) Result { +func normalizeTrimRight(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(strings.TrimRight(value.String(), " \t")) - return ResultValid + return nil } diff --git a/trim_right_test.go b/trim_right_test.go index 6adb417..88fda32 100644 --- a/trim_right_test.go +++ b/trim_right_test.go @@ -23,7 +23,7 @@ func TestNormalizeTrimRightNonString(t *testing.T) { checker.Check(user) } -func TestNormalizeTrimRightResultValid(t *testing.T) { +func TestNormalizeTrimRightErrValid(t *testing.T) { type User struct { Username string `checkers:"trim-right"` } diff --git a/trim_test.go b/trim_test.go index 876370d..7648840 100644 --- a/trim_test.go +++ b/trim_test.go @@ -23,7 +23,7 @@ func TestNormalizeTrimNonString(t *testing.T) { checker.Check(user) } -func TestNormalizeTrimResultValid(t *testing.T) { +func TestNormalizeTrimErrValid(t *testing.T) { type User struct { Username string `checkers:"trim"` } diff --git a/upper.go b/upper.go index 9b9de87..a0a101e 100644 --- a/upper.go +++ b/upper.go @@ -19,12 +19,12 @@ func makeUpper(_ string) CheckFunc { } // normalizeUpper maps all Unicode letters in the given value to their upper case. -func normalizeUpper(value, _ reflect.Value) Result { +func normalizeUpper(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(strings.ToUpper(value.String())) - return ResultValid + return nil } diff --git a/upper_test.go b/upper_test.go index 1d52cee..6e0fb8f 100644 --- a/upper_test.go +++ b/upper_test.go @@ -23,7 +23,7 @@ func TestNormalizeUpperNonString(t *testing.T) { checker.Check(user) } -func TestNormalizeUpperResultValid(t *testing.T) { +func TestNormalizeUpperErrValid(t *testing.T) { type User struct { Username string `checkers:"upper"` } diff --git a/url.go b/url.go index a53d3ff..b43efb3 100644 --- a/url.go +++ b/url.go @@ -6,6 +6,7 @@ package checker import ( + "errors" "net/url" "reflect" ) @@ -13,25 +14,25 @@ import ( // CheckerURL is the name of the checker. const CheckerURL = "url" -// ResultNotURL indicates that the given value is not a valid URL. -const ResultNotURL = "NOT_URL" +// ErrNotURL indicates that the given value is not a valid URL. +var ErrNotURL = errors.New("please enter a valid URL") // IsURL checks if the given value is a valid URL. -func IsURL(value string) Result { +func IsURL(value string) error { url, err := url.ParseRequestURI(value) if err != nil { - return ResultNotURL + return ErrNotURL } if url.Scheme == "" { - return ResultNotURL + return ErrNotURL } if url.Host == "" { - return ResultNotURL + return ErrNotURL } - return ResultValid + return nil } // makeURL makes a checker function for the URL checker. @@ -40,7 +41,7 @@ func makeURL(_ string) CheckFunc { } // checkURL checks if the given value is a valid URL. -func checkURL(value, _ reflect.Value) Result { +func checkURL(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } diff --git a/url_escape.go b/url_escape.go index a41784e..f78abe2 100644 --- a/url_escape.go +++ b/url_escape.go @@ -20,12 +20,12 @@ func makeURLEscape(_ string) CheckFunc { // normalizeURLEscape applies URL escaping to special characters. // Uses net.url.QueryEscape for the actual escape operation. -func normalizeURLEscape(value, _ reflect.Value) Result { +func normalizeURLEscape(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } value.SetString(url.QueryEscape(value.String())) - return ResultValid + return nil } diff --git a/url_test.go b/url_test.go index ce97f90..883eb0a 100644 --- a/url_test.go +++ b/url_test.go @@ -12,22 +12,22 @@ import ( ) func ExampleIsURL() { - result := checker.IsURL("https://zdo.com") - if result != checker.ResultValid { + err := checker.IsURL("https://zdo.com") + if err != nil { // Send the mistakes back to the user } } func TestIsURLValid(t *testing.T) { - result := checker.IsURL("https://zdo.com") - if result != checker.ResultValid { + err := checker.IsURL("https://zdo.com") + if err != nil { t.Fail() } } func TestIsURLInvalid(t *testing.T) { - result := checker.IsURL("https:://index.html") - if result == checker.ResultValid { + err := checker.IsURL("https:://index.html") + if err == nil { t.Fail() } } diff --git a/url_unescape.go b/url_unescape.go index a115689..d10e602 100644 --- a/url_unescape.go +++ b/url_unescape.go @@ -20,7 +20,7 @@ func makeURLUnescape(_ string) CheckFunc { // normalizeURLUnescape applies URL unescaping to special characters. // Uses url.QueryUnescape for the actual unescape operation. -func normalizeURLUnescape(value, _ reflect.Value) Result { +func normalizeURLUnescape(value, _ reflect.Value) error { if value.Kind() != reflect.String { panic("string expected") } @@ -30,5 +30,5 @@ func normalizeURLUnescape(value, _ reflect.Value) Result { value.SetString(unescaped) } - return ResultValid + return nil }