Laravel’s powerful validation rules

|
| By Webner

Laravel’s powerful validation rules

When we develop any application in Laravel, various validation rules are available which are used to validate data from all incoming HTTP requests.

Some Examples:

1. First let’s create a controller named RegistrationController by executing the following command:

php artisan make:controller RegistrationController --plain

2. Create a view file named as “registration.blade.php” in folder resources/views/.

3. Then we create two methods in RegistrationController file:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class RegistrationController extends Controller {
   public function registrationform(){
      return view(‘registration’);
   }
   public function validateform(Request $request){
    //Validate form fields
   }
}

4. Now, we create the registration form in registration.blade.php file:

<html>   
   <head>
   <title>Registration Form</title>
   </head>
   <body> 
   @if (count($errors) > 0)
      <div class = "alert alert-danger">
         <ul> @foreach ($errors->all() as $error)
               <li>{{ $error }}</li>
            @endforeach
         </ul>
      </div>
   @endif 
   <?php echo Form::open(array('url'=>'/validation')); ?>
     <table border='1'>
     <tr> <td align='center' colspan='2'>Registration</td>  </tr>
     <tr>      <td>Company Name</td>
     <td><?php echo Form::text('company_name'); ?></td>
     </tr>
     <tr>      <td>Username</td>
     <td><?php echo Form::text('username'); ?></td>
     </tr>
     <tr>  <td>Email</td>
     <td><?php echo Form::text('email'); ?></td>
     </tr>
     <tr>  <td>Password</td>
     <td><?php echo Form::password('password'); ?></td>
     </tr>
     <tr>  <td>Expiration Date</td>
     <td><?php echo Form::text('expiration_date'); ?></td>
     </tr>
     <tr>  <td>Profile Image</td>
     <td><?php echo Form::file('profile_image'); ?></td>
     </tr>
     <tr>  <td>Hobbies</td>
     <td><?php echo Form::checkbox('hobbies[]','Cooking'); ?>
           {{Form::label('Title','Cooking')}}
    <?php echo Form::checkbox('hobbies[]','Music'); ?>
           {{Form::label('Title','Music')}}  
 </td>
     </tr>
     <tr>  <td>Gender</td>
     <td><?php echo Form::radio('gender','1'); ?>
           {{Form::label('Title','Male')}}
    <?php echo Form::radio('gender','0'); ?>
           {{Form::label('Title','Female')}}
     <?php echo Form::radio('gender','2'); ?>
           {{Form::label('Title','Other')}}  
 </td>
    </tr>
    <tr>  <td align='center' colspan='2'> <?php echo Form::submit('Login'); ?> </td> </tr>
    </table>
     <?php  echo Form::close (); ?>
   </body>
</html>

5. Then, we set up the route in app/Http/routes.php file:

Route::get('/validation','RegistrationController@registrationform');
Route::post('/validation','RegistrationController@validateform');

//VALIDATION RULES

6: Before running the application, we can validate all incoming HTTP requests by using various powerful validation rules.
For example, we are setting these validation rules in “validateform” method in “RegistrationController”.

public function validateform(Request $request){
                     $this->validate($request,[
'company_name'=>'required|size:10',
   'username'=>'required|string|max:8',
         'email' => 'required|email|unique:users',
         'password'=>'required|min:8',
         'expiration_date' =>'required|after:'.date('Y-m-d'),
   'profile_image' => 'required|image',
   'hobbies' => 'required|array',
   'gender' =>'required|boolean'
    ]);
}

List of validation rules used in above example:

a) required:->
Input field must not be blank if we apply “required” validation rule on this. In above example, all fields must have some value.

b) string:->
If you want to validate your input field that must accepts only string then use this validation rule. In above example, we applied this rule on “username” field.

c) max:->
The field under this validation must have a Maximum value in size. In above example, “username” field can have maximum 8 characters. If character length exceeds 8, then it will thrown an error.

d) min:->
This rule defines the minimum value in a size for a field. In above example,”password” field must be greater than or minimum value to 8 characters. If character length less than 8, then it will thrown an error.

e) email:->
It validates an e-mail address. In above example, the input field “email” takes only email-address.

f) unique (Database): When you want to compare the input fields value with database table values then you can apply this validation rule on input field. This rule prevents user from entering existing data into selected field. In above example, by using this rule on email input field, you can not store same value for more than one users in email column of “users” table in database.

g) after:date:->It validates the date and value must be after the given date. The dates value will be passed into the PHP strtotime function. In above example :the validation on “expiration_date” field will check given date must be after today’s date.

h) image:->If you want to validate your input field must be an image then you can use this method. You can upload only those images which will have image type (jpeg, png, bmp, gif, or svg), otherwise it will throws an error.

i) array:->The field under this validation must be an array. For example,a user can have more than one hobbies, so you can post data of this input field by making this as array. In above example,”hobbies” input field is an example of this validation rule.

j) boolean:->
The field under this validation must be a boolean value. Accepted values are true, false, 1, 0, “1”, and “0”.

k) size:value
If you want to validate size of any input field that must have a matching of given value then this is the method. In above example, we are applying this rule on “company_name” field.

7. Now, we can run our application by typing following url:
http://localhost:8000/validation

For example:

(A).

(B). Error message for all fields which are not filled:

(C).Specific error message for specific validation rule:

Leave a Reply

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