The examples on this site are currently tested to work on Phalcon V3.4 and Phalcon Devtools V3.2 Some issues may arise when using later versions.

Please get in touch or post a comment below the post if you encounter a problem.

Edit the file /app/models/Member.php which you created in the Step 1 - Scaffolding post from the getting started. At the top of the class add the following use statements.


use Phalcon\Validation;
use Phalcon\Validation\Validator\Date as DateValidator;

The "use" function allows us to use namespaces. Namespaces are a way to import classes from other locations and to alias them. Aliasing the classes allows us to give them a temporary name which will avoid collisions with names which may have already been used in the code. This approach is broadly equivalent to "importing" in other programming languages and allows us to keep code organised and assists with the overall re-usability of code.

Add the end of the class add the following function

public function validation()
{
   $validator= new Validation();
   $dValidator = new DateValidator(["message" => "please use the format yyyy-mm-dd",
					"format" => "Y-m-d"]);
   $validator->add('dateofbirth', $dValidator);
   return $this->validate($validator);
}

The validation function instantiates a new validation class. A new DateValidator object is then instantiated, added to the validation object and associated with the dateofbirth attribute. 

This validation function overrides the abstract validate function in the abstract class Phalcon\Mvc\Model. The validate function will test any and all validators which have been added for attributes of the model.

Now if a users enters a date in the format other than yyyy-mm-dd, and submits the form, the following message appears on the next view (which the controller action has directed them to using the dispatcher).


It makes sense that if there is a validation error the user would be directed back to retry the same action.