Forms? Keep the validation rules inside the model

As always, when talking about forms we also talk about validation. For a long time I’ve validated the forms inside the controllers because it is fast and simple – no more browsing between files.

But after a while you find yourself having a controller which is becoming more complex and bigger. So why not keep at least the validation rules somewhere else?

One solution would be to keep all the validation rules inside a config file, and organize the rules into “groups”. I will talk about this method in another post.

The other solution would be to put the validation rules inside the model, which, in my opinion would make more sense, considering that every form element is actually a column inside your database tables.

As you can see, you can make an array that contains different rules depending on the forms that are used. The array is public, so that it can be accessed directly by the controller. Regarding password, there will be alot of people arguing that I can’t just verify plain password against the database and that the password needs to be encrypted. Yet this is not the scope of this post. I only wanted to give an example about how to keep the rules inside the model.

Now, going to the controller, you simply call the rules:

I won’t go and make the view, that not being the point of this post. The only thing I hope you understand is that every form element must be named exactly like the keys inside the array we defined in the model (first_name, last_name, email, password, etc.).

0 thoughts on “Forms? Keep the validation rules inside the model

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

No spam? * Time limit is exhausted. Please reload CAPTCHA.