Form Validation with CakePHP

This tutorial is an extension of our CRUD. I will not repeat the normal code except the validation code. If you want to go through this tutorial, please read the previous tutorial first. Otherwise you may be puzzled.

Cake logo

Form validation is a process of justification, are we giving valid data or not. Almost all frameworks have their own process of form validation. CakePHP also is not different. The only difference is we will put our validation code inside our model. CakePHP has it’s own rules of form validation. I am going to show you some of those and the procedure.

Validation

As I told you already, we will only change our model class from our CRUD. Rest of the code will be same.

So, open your model class app/Model folder named Post.php

App::uses('AppModel', 'Model');
/**
 * Post Model
 *
 * @property User $User
 */
class Post extends AppModel {

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'title' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'body' => array(
			'notEmpty' => array(
				'rule' => array('notEmpty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

After placing the above code, your form will be look as follows, if you want to keep it blank and press submit button.

Conclusion:
This is a very small tutorial, as we have only changed our model class. The purpose of this tutorial is showing you, how you can validate your from in a very easy way.

Happy Coding.. 🙂

Form Validation with CakePHP

Hej, I’m from Bangladesh. Learning programming is one of the freaking decisions I have taken in my life. Because, it makes me and my life crazy. I have great weakness on open source technologies. Perhaps, that’s why I do not know any closed source language. I fall in love with programming, when I started my undergraduate in East West University. Till now, I can not live without it.
Print Friendly

Leave a Reply

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

*