Skip to content

Commit

Permalink
validation
Browse files Browse the repository at this point in the history
  • Loading branch information
iesreza committed Jun 7, 2024
1 parent f089dd0 commit 4e1a2f8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/validation/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package validation

import (
"fmt"
"github.com/getevo/evo/v2/lib/db"
"github.com/getevo/evo/v2/lib/generic"
"reflect"
)
Expand Down Expand Up @@ -36,6 +37,25 @@ func validateField(g *generic.Value, field *reflect.StructField) error {
validators := parseValidators(field.Tag.Get("validation"))
for _, validator := range validators {
var found = false
for r, fn := range DBValidators {
if match := r.FindStringSubmatch(validator); len(match) > 0 {
found = true
var stmt = db.Model(g.Input).Statement
var err = stmt.Parse(g.Input)
if err != nil {
return err
}

err = fn(match, &value, stmt, stmt.Schema.FieldsByName[field.Name])
tag := field.Tag.Get("json")
if tag == "" {
tag = field.Name
}
if err != nil {
return fmt.Errorf("%s %s", tag, err)
}
}
}
for r, fn := range Validators {
if match := r.FindStringSubmatch(validator); len(match) > 0 {
found = true
Expand Down
28 changes: 28 additions & 0 deletions lib/validation/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@ package validation

import (
"fmt"
"github.com/getevo/evo/v2/lib/db"
"github.com/getevo/evo/v2/lib/generic"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"net/url"
"regexp"
"strconv"
"strings"
"unicode"
)

var DBValidators = map[*regexp.Regexp]func(match []string, value *generic.Value, stmt *gorm.Statement, field *schema.Field) error{
regexp.MustCompile("^unique$"): uniqueValidator,
regexp.MustCompile("^fk$"): foreignKeyValidator,
}

var Validators = map[*regexp.Regexp]func(match []string, value *generic.Value) error{
regexp.MustCompile("^text$"): textValidator,
regexp.MustCompile("^alpha$"): alphaValidator,
Expand All @@ -29,6 +37,26 @@ var Validators = map[*regexp.Regexp]func(match []string, value *generic.Value) e
regexp.MustCompile(`^ip$`): ipValidator,
}

func uniqueValidator(match []string, value *generic.Value, stmt *gorm.Statement, field *schema.Field) error {
var c int64
db.Where(field.DBName+" = ?", value.Input).Table(stmt.Table).Count(&c)
if c > 0 {
return fmt.Errorf("duplicate entry")
}
return nil
}

func foreignKeyValidator(match []string, value *generic.Value, stmt *gorm.Statement, field *schema.Field) error {
var c int64
//field.Tag.Get("")
//scm.Find()
db.Where(field.DBName+" = ?", value.Input).Table(stmt.Table).Count(&c)
if c > 0 {
return fmt.Errorf("duplicate entry")
}
return nil
}

func textValidator(match []string, value *generic.Value) error {
var v = value.String()
if v == "" {
Expand Down

0 comments on commit 4e1a2f8

Please sign in to comment.