In this video, Justin will demonstrate creating your own custom validation rules for a CakePHP 3 application. You will learn how to add and create custom validation rules to ensure any specific validation that is not covered using the CakePHP 3 core validation class can be added to your application.
- [Voiceover] What happens if we want to validate for something that we can't use one of the many tools that CakePHP provides for us? Well, in that case, you could write custom validation methods. For instance, in our application, we want to prevent people from using the URL of the bookmark as the name of the bookmark itself. We can do this very easily using a custom validation method. To begin, we need to edit bookmarks validation. This occurs in the table class. So we need to open the file at src, Model, Table, BookmarksTable.php.
Let's first add a rule to ensure our URLs are actually URLs, since currently that isn't in place. So, recall from the prior video to do this we edit the validation default method on line 51. And we need to edit the validation rules for the URL, which is on line 61. And edit line 63 to remove the semi-colon, and then add a new line that reads as - >add('url', 'url', an array with an initial key of 'rule' set equal to another array with a value of 'url' and add your semi-colon.
Recall what exactly this is doing. This says to add a validation rule for the URL field, the rule error being called url, and the rule method to call is url. An exercise, if you have a good handle on iterators and closures, is to dive through the CakePHP core and start piecing together exactly how this works. It's a really interesting design. You may already have some guesses just based on the design of this method call. Ok, what next? We want to add a custom rule that says the title cannot be a URL.
So let's start with this. What might the pattern look like based on the just-added rule for the URL column? First, we need to edit the title validation. So we'll add a new line on 59. We'll delete the semi-colon. Add a new line, and we'll do -> and again, we're going to be adding validation rules for the title column field. So it's probably going to follow the format of add('title', and then we have the name of the error field that we want, in this case we'll call it 'notURL'.
Next, this is in the past where we pass an array of options. One of which was our rule method. However, in this case, we don't have a rule method to determine if the value is not a URL. We'll need to write our own. So to do this, we can use a custom method and then write method here in our table class and say that method is a rule that will use th-ruh-n, that will determine if the title column is valid or not. Ok, so I added empty array as the third parameter to the add method.
And then we went to add the key value pair of ['rule' => 'notUrl']) And add your semi-colon at the end. So now we need to tell the validator class where to find our method. As it is, it would try looking in the class with all the other validation rule methods and fail to find it, and then display an error, and then we wouldn't be happy with our code. So, instead, we need to pass a key provider, and a value of table. Provider says where to look for this method, and the value of table says to look for this in the table class.
So first, I'm going to clean up line 60. And move my array keys to be on separate lines. And add the closing brace for my array and the method call to its own line on line 62. And add a new line that has the string key 'provider' and the string value of 'table'. And finally, we haven't covered this yet. But, you recall how our error messages on the fields have been pretty generic up to this point. We can, in this array, also pass a custom message that gets displayed.
So, if we add the key value pair of 'message' and set it to 'The title field can not be a url', Great. So we added a new custom validation method to our title column. But now we need to actually write the method. So, how do we do this? It's actually pretty easy, right? We know CakePHP knows how to determine if something is a URL, so all we need to do is simply take that and return the inverse. Let's begin by creating a method in our table class.
Scroll down to the bottom of this class, and on line 85 add a few blank lines. And let's start our new method on line 87. Let's write out public function notURL Validation methods take two parameters. The first is the value of the field being checked, and the second is a context array that includes contextual data about the validation operation. So we'll add the parameters $value, array $context to the method definition.
What next, we'll add our opening and closing braces. And now we need to call the URL validation method. Passing in our value, and then return to negation of that return from that method. A little bit complicated, so let's break it down. First, we need the URL validation method CakePHP uses. You could dive through the API and documentation to figure this all out. However, I already know what it is. The validation clause in the Cake validation namespace has the static methods used for validation.
Including one called URL. So line 89 will look like \Cake, \Validation, \Validation, ::url, and passing the value to our method call. This is calling the namespace class validation and the static method URL. Now we want to return the inverse of this method call so we can wrap it in parentheses, and then use an exclamation mark to inverse it, and then return it.
Don't forget about your semi-colon. And there we go. We just built our own custom validation method. Let's see it working. First, remember to start your CakePHP server and then go to the bookmarks index page in your browser. Now we need to edit a bookmark. In this case, I'm just going to go ahead and edit the first one. If we copy the URL field, and paste it in as the Title, and hit Submit, we'll see that this will fail, which is exactly what we wanted.
We created a custom validation rule that ensures our users cannot submit titles that are URLs. CakePHP also includes the ability to write custom application rules that you may find useful if you need to compare data across tables to validate something.
CakePHP is a critical framework for PHP developers. It helps them build complex web applications faster and more efficiently. If you want to use CakePHP 3 (the latest version of the framework) in your own development workflow, this is the place to start.
Justin Yost provides an overview of the underlying MVC pattern in CakePHP, and the installation and configuration process for Mac and Windows. He shows how to use the CakePHP shell to build your first basic CakePHP app, and then discusses each application element in depth: controllers, models, views, components, behaviors, helpers, and utilities. At each step, he discusses the relevant new features and enhancements in CakePHP 3, including new components; performance, session management, and ORM improvements; and localization.
In later chapters, the course gets a little more advanced. Watch these tutorials to learn how to send email with CakePHP, extend CakePHP with plugins, and write unit tests to identify and eliminate bugs in your code. Justin also shows how to add security to your CakePHP apps with a basic user authentication system.
- Installing and configuring CakePHP
- Using the CakePHP shell console
- Creating CakePHP controllers
- Saving data in a CakePHP model
- Finding and deleting data
- Working with entity methods
- Creating CakePHP views
- Using and customizing components to share functionality between controllers
- Creating behaviors
- Formatting data with helpers
- Developing faster with CakePHP utilities: hash, collections, and logging
- Sending CakePHP email
- Creating a custom plugin
- Testing CakePHP applications
- Authorizing users of CakePHP applications