Skip to content

Automatic validation #240

@vcraescu

Description

@vcraescu

The entire entity validation logic should be reimplemented. I believe it's wrong how it works now because it makes almost impossible to use it at all. See the following scenario.

Controller

func (c *MyController) Edit(id string, frm *forms.MyForm) {
	var m models.MyModel

	c.findOr404(id, &m)

	if c.Req.Method == "POST" {
        // where i want to validate my form before save 
        }
}

This request will always fail even it is just a GET request and frm is supposed to be zero because nothing was submitted yet. Even If i remove any validation tags from forms.MyForm and put them directly on models.MyModel just to overcome this issue, but If forms.MyForm has any reference to a model which has validation tags again it will fail. Spent so much time fighting this behaviour.

Having a single HandleError method is a very bad idea in my opinion because when you end up in HandleError method your context is lost. You don't know the action where the error occurred and how you're supposed to handle it. You just end up with an error object you have to deal with but you don't know how. In the wild that's not always the case. Validation can be complex and might have a lot of logic behind and it needs to be very flexible. Magic kills flexibility. This might make sense If we would have single action controllers or single verb per action. But as longs as you have multiple verbs per action you gonna have a really bad day. :sad:

A better approach would be to remove any automatic validation and let the user handle it. I mean the context could have a method Validate(m interface{}) which is just a proxy to validator and let the programmer validate the objects he needs. Something like below:

func (c *MyController) Edit(id string, frm *forms.MyForm) {
	var m models.MyModel

	c.findOr404(id, &m)

	if c.Req.Method == "POST" {
        	if formErrors := c.Validate(m); len(formErrors) > 0 {
			data["FormErrors"] = formErrors
			c.render(data)
			return
		}
                // save
        }
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions