-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.go
72 lines (62 loc) · 1.91 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"net/http"
"regexp"
"time"
"github.com/gin-gonic/gin"
)
func validateReceipt(c *gin.Context) {
var r receipt
if err := c.ShouldBindJSON(&r); err != nil {
errorMessage, _ := fmt.Printf("Invalid JSON: %v", err.Error())
c.JSON(http.StatusBadRequest, gin.H{"error": errorMessage})
c.Abort()
return
}
// Validate retailer name
if !regexp.MustCompile(`^[\w\s\-]+$`).MatchString(r.Retailer) {
fmt.Printf("%v is an invalid retailer name!\n", r.Retailer)
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid retailer name"})
c.Abort()
return
}
// Validate total amount
if !regexp.MustCompile(`^\d+\.\d{2}$`).MatchString(r.Total) {
fmt.Printf("%v is an invalid total amount!\n", r.Total)
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid total amount"})
c.Abort()
return
}
// Validate items
for _, item := range r.Items {
if !regexp.MustCompile(`^[\w\s\-]+$`).MatchString(item.ShortDescription) {
fmt.Printf("%v is an invalid item's short description!\n", item.ShortDescription)
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid short description"})
c.Abort()
return
}
if !regexp.MustCompile(`^\d+\.\d{2}$`).MatchString(item.Price) {
fmt.Printf("%v is an invalid item's price!\n", item.Price)
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid price"})
c.Abort()
return
}
}
// Validate purchase date
if _, err := time.Parse("2006-01-02", r.PurchaseDate); err != nil {
fmt.Printf("%v is an invalid purchase date!\n%v\n", r.PurchaseDate, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid purchase date"})
c.Abort()
return
}
// Validate purchase time
if _, err := time.Parse("15:04", r.PurchaseTime); err != nil {
fmt.Printf("%v is an invalid purchase time!\n%v\n", r.PurchaseTime, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid purchase time"})
c.Abort()
return
}
c.Set("validatedReceipt", r)
c.Next()
}