aboutsummaryrefslogtreecommitdiff
path: root/customer/validators.go
diff options
context:
space:
mode:
authorVidhu Kant Sharma <vidhukant@vidhukant.com>2023-09-03 22:29:46 +0530
committerVidhu Kant Sharma <vidhukant@vidhukant.com>2023-09-03 22:29:46 +0530
commit46083ff15e16b0b49132af9466bcab7c2ae71322 (patch)
treebc29d36293c459342c90d6f89b19c8be666ed327 /customer/validators.go
parent620fb2f89b5acd70af4ed075b4797f81a3f1d109 (diff)
validating phone number and websitev0.0.4
Diffstat (limited to 'customer/validators.go')
-rw-r--r--customer/validators.go25
1 files changed, 24 insertions, 1 deletions
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)