validate icon indicating copy to clipboard operation
validate copied to clipboard

Wondering how to implement a Unique validator

Open zinefer opened this issue 5 years ago • 0 comments

I am working on a project in Buffalo that requires a model have a Unique but user configurable string field. Is there any particular way I should go about passing the tx into the validator?

Doing this seems to work:

type FieldIsUnique struct {
	Table string
	Name  string
	Field string
	tx *pop.Connection
}

func (v *FieldIsUnique) IsValid(errors *validate.Errors) {
	exists, err := v.tx.Where(fmt.Sprintf("%s = ?", v.Name), v.Field).Exists(v.Table)
	if exists || err != nil {
		errors.Add(strings.ToLower(v.Name), fmt.Sprintf("%s is already in use", v.Field))
	}
}

func (m *Model) Validate(tx *pop.Connection) (*validate.Errors, error) {
	return validate.Validate(
		&FieldIsUnique{Table: "models", Field: m.WannaBeUnique, Name: "WannaBeUnique", tx: tx},
	}, nil
}

But I am wondering if there is a better pattern I should follow...

zinefer avatar Nov 30 '19 07:11 zinefer