Update validation package to work with `generation.Parameters` type

This commit is contained in:
Fred Boniface 2023-09-02 21:04:29 +01:00
parent cc08f8358e
commit d3bd2673e8
2 changed files with 13 additions and 9 deletions

View File

@ -1,29 +1,33 @@
package validation
import "fmt"
import (
"fmt"
func Validate(input string, format string) bool {
rule, exists := FormatRules[format]
"git.fjla.uk/fred.boniface/barcodes/generation"
)
func Validate(params generation.Parameters) bool {
rule, exists := FormatRules[string(params.Format)]
if !exists {
fmt.Printf("Error: No rule found for format '%s'\n", format)
fmt.Printf("Error: No rule found for format '%s'\n", params.Format)
return false
}
if uint64(len(input)) < rule.minLength || uint64(len(input)) > rule.maxLength {
if uint64(len(params.Content)) < rule.minLength || uint64(len(params.Content)) > rule.maxLength {
fmt.Printf("Validation Error: Length must be between %d and %d\n", rule.minLength, rule.maxLength)
return false
}
if !rule.charset.MatchString(input) {
if !rule.charset.MatchString(params.Content) {
fmt.Println("Validation Error: Contains illegal characters")
return false
}
if uint64(len(input))%uint64(rule.divisible) != 0 {
if uint64(len(params.Content))%uint64(rule.divisible) != 0 {
fmt.Printf("Validation Error: Length must be a multiple of %d", rule.divisible)
return false
}
fmt.Printf("Validation passed for barcode type %s\n", format)
fmt.Printf("Validation passed for barcode type %s\n", params.Format)
return true
}

View File

@ -26,7 +26,7 @@ func generateBarcode(w http.ResponseWriter, r *http.Request) {
Content: req.Content,
}
validate := validation.Validate(req.Content, req.BarcodeType)
validate := validation.Validate(parameters)
if !validate {
fmt.Println("Validation Failed")
http.Error(w, "Validation Failed", http.StatusBadRequest)