From 46083ff15e16b0b49132af9466bcab7c2ae71322 Mon Sep 17 00:00:00 2001 From: Vidhu Kant Sharma Date: Sun, 3 Sep 2023 22:29:46 +0530 Subject: validating phone number and website --- customer/validators.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'customer') diff --git a/customer/validators.go b/customer/validators.go index 482d532..086750f 100644 --- a/customer/validators.go +++ b/customer/validators.go @@ -21,10 +21,17 @@ import ( "regexp" "strings" "net/mail" + "net/url" "vidhukant.com/openbills/errors" e "errors" ) +var phoneRegex, gstinRegex, urlRegex *regexp.Regexp +func init() { + phoneRegex = regexp.MustCompile(`^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$`) + gstinRegex = regexp.MustCompile(`^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$`) +} + // NOTE: very inefficient and really really really dumb but it works // TODO: find a better (or even a remotely good) way func checkDuplicate(field, value string, userId uint) error { @@ -69,7 +76,7 @@ func (c *Customer) validate() error { // don't validate if GSTIN is empty if c.Gstin != "" { // GSTIN regex validation - match, _ := regexp.MatchString("^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$", c.Gstin) + match := gstinRegex.MatchString(c.Gstin) if (!match) { return errors.ErrInvalidGSTIN } @@ -99,6 +106,22 @@ func (c *Customer) validate() error { } } + // don't validate phone if empty + if c.Phone != "" { + match := phoneRegex.MatchString(c.Phone) + if (!match) { + return errors.ErrInvalidPhone + } + } + + // don't validate website if empty + if c.Website != "" { + _, err := url.ParseRequestURI(c.Website) + if err != nil { + return errors.ErrInvalidWebsite + } + } + var err error for _, i := range [][]string{{"phone", c.Phone}, {"email", c.Email}, {"website", c.Website}} { err = checkDuplicate(i[0], i[1], c.UserID) -- cgit v1.2.3