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.
Once Upon a Time
At some point in time, you probably did your data validation like this:
<?php
$errors = array();
if ( empty( $_POST['name'] ) || ! is_string( $_POST['name'] ) ) {
$errors[] = 'Name is required';
} elseif ( ! preg_match( "/^[A-Za-z\s-_]+$/", $_POST['name'] ) ) {
$errors[] = 'Name can have only alphabets, spaces and dashes';
}
if ( empty( $_POST['email'] ) || ! is_string( $_POST['email'] ) ) {
$errors[] = 'Email is required';
}
//...........
//.... some more code here
//...........
//display errors
if ( ! empty( $errors ) ) {
for ( $i = 0; $i < count( $errors ); $i++ ) {
echo '<div class="error">' . $errors[ $i ] . '</div>';
}
}
Well, that was the stone age for you. Luckily we have much much better and sophisticated validation packages these days (and have had them for quite some time in PHP).
If you use any application framework as the foundation of your app, chances are it will have its own or a recommended 3rd party data validation package, especially if it is a full stack framework. Since Laravel is a full stack framework, it comes with its own validation package. As always, you’re not constrained to use that and can use any other data validation package that you want. However, for the purpose of this tutorial, we will stick with what comes with Laravel by default.
Continue reading %Data Validation in Laravel: The Right Way%