The SitePoint PHP blog has posted the first two parts of a new series looking at how to do data validation in Laravel, a popular PHP framework. Laravel comes with a set of included validators that can easily be used to check incoming data. This article series introduces them and the features they can provide.
If an app was a world then data would be its currency. Every app, no matter what its purpose, deals in data. And almost every type of app works with user input, which means it expects some data from users and acts on it accordingly. But that data needs to be validated to make sure it is of correct type and a user (with nefarious intent) is not trying to break or crack into your app. Which, if you are making an application which requires user input, is why you would need to write code to validate that data as well before you do anything with it.
In the first part of the series they start with an example of doing validation the "old way". They reproduce this same validation using the Laravel validators and show how to introduce it as a service to the overall application. Their "RocketCandy" validation service can then handle the same validations and make for a cleaner interface in the calling script. It's refactored even more to include exceptions when the validation fails and the HTML for outputting the error messages thrown. Unit tests are also included to ensure things are working as they should.
In the second part of the series they build on the examples from part one and introduce custom validators. An example of validation around dashes, spaces and alphanumeric data is included (using regular expressions) and how they can be defined as custom validation rules.