aboutsummaryrefslogtreecommitdiff
path: root/customer/validators.go
diff options
context:
space:
mode:
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)