From 86faadca64d1e1306793b39e479c2e69c78419da Mon Sep 17 00:00:00 2001 From: "luke.rodham" Date: Thu, 12 Jul 2018 09:49:26 +0100 Subject: [PATCH] master: added functionality to IsValid --- checker.go | 10 ++++++++++ checker_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/checker.go b/checker.go index 5735a60..04b4983 100644 --- a/checker.go +++ b/checker.go @@ -2,12 +2,22 @@ package checker import ( "fmt" + "regexp" "strings" ) +var ( + emailRegex = "^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:\\(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22)))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" +) + // IsValid preform a simple validation check to see if the email is correctly formatted. // An error is returned if not. func IsValid(email string) error { + emailRegex := regexp.MustCompile(emailRegex) + if !emailRegex.MatchString(email) { + return fmt.Errorf("invalid email") + } + return nil } diff --git a/checker_test.go b/checker_test.go index 2a28bfe..b78fa14 100644 --- a/checker_test.go +++ b/checker_test.go @@ -51,3 +51,30 @@ func TestIsGeneric(t *testing.T) { } } } + +func TestIsValid(t *testing.T) { + tests := []struct { + Email string + ShouldError bool + }{ + { + Email: "example@asdas_-3-43222.com", + ShouldError: true, + }, + { + Email: "example--3-43222.com", + ShouldError: true, + }, + { + Email: "example@hotmail.com", + ShouldError: false, + }, + } + + for _, test := range tests { + err := checker.IsValid(test.Email) + if err != nil && test.ShouldError == false { + t.Error(err) + } + } +}