diff --git a/lib/validation/validation.go b/lib/validation/validation.go index f8e2076..dbbc611 100644 --- a/lib/validation/validation.go +++ b/lib/validation/validation.go @@ -2,6 +2,7 @@ package validation import ( "fmt" + "github.com/getevo/evo/v2/lib/db" "github.com/getevo/evo/v2/lib/generic" "reflect" ) @@ -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 diff --git a/lib/validation/validators.go b/lib/validation/validators.go index 524b8e3..346eede 100644 --- a/lib/validation/validators.go +++ b/lib/validation/validators.go @@ -2,7 +2,10 @@ 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" @@ -10,6 +13,11 @@ import ( "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, @@ -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 == "" {