Using advanced validation laravel in forms

There might be times when we need to validate our forms for something that’s not part of the
framework. This recipe will show you how to build a custom validation rule and apply it.

Getting ready

For this recipe, we need a standard installation of Laravel.

How to do it…

The following are the steps to complete this recipe:
1. In the views directory, create a file named valid.php to hold our form using the
following code:
<!doctype html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>Custom Validation</title>
</head>
<body>
<p>
<?php if ($errors): ?>
<?php echo $errors->first(’email’) ?>
<?php echo $errors->first(‘captain’) ?>
<?php endif; ?>
</p>
<p>
<h3>Custom Validation</h3>
<?= Form::open(array(‘url’ => ‘valid’, ‘method’ => ‘post’))
?>
<?= Form::label(’email’, ‘Email’) ?>
<?= Form::text(’email’) ?><br><br>
<?= Form::label(‘captain’, ‘Your favorite captains (choose
three)’) ?><br>
<?= ‘Pike: ‘ . Form::checkbox(‘captain[]’, ‘Pike’) ?><br>
<?= ‘Kirk: ‘ . Form::checkbox(‘captain[]’, ‘Kirk’) ?><br>

<?= ‘Picard: ‘ . Form::checkbox(‘captain[]’, ‘Picard’)
?><br>
<?= ‘Sisko: ‘ . Form::checkbox(‘captain[]’, ‘Sisko’) ?><br>
<?= ‘Janeway: ‘ . Form::checkbox(‘captain[]’, ‘Janeway’)
?><br>
<?= ‘Archer: ‘ . Form::checkbox(‘captain[]’, ‘Archer’)
?><br>
<?= ‘Crunch: ‘ . Form::checkbox(‘captain[]’, ‘Crunch’)
?><br>
<?= Form::submit(‘Submit’) ?>
<?= Form::close() ?>
</p>
</body>
</html>

2. In the routes.php file, create our routes with the following code:
Route::get(‘valid’, function()
{
return View::make(‘valid’);
});
Route::post(‘valid’, function()
{
$rules = array(’email’ => ‘required|email’,
‘captain’ => ‘required|check_three’);
$messages = array(
‘check_three’ => ‘Thou shalt choose three captains. No
more. No less. Three shalt be the number thou shalt
choose, and the number of the choosing shall be
three.’,);
$validation = Validator::make(Input::all(), $rules,
$messages);
if ($validation->fails())
{
return Redirect::to(‘valid’)->withErrors($validation);
}
echo “Form is valid!”;
});
3. Also in the routes.php file, create our custom validation as given in the
following code:
Validator::extend(‘check_three’, function($attribute,
$value, $parameters)
{
return count($value) == 3;
});

How it works…

To begin, we create the form in our view. We ask for a valid e-mail and exactly three of the
checkboxes to be checked. Since there’s no Laravel validation method for exactly three
checkboxes, we need to create a custom validation.
Our custom validation takes the input array and does a simple count. If it comes up to three, it
returns TRUE. If not, it returns FALSE and fails the validation.
Back in our form processing route, all we then need to do is add the name of the custom
validator we created to our validation rules. If we want to set a custom message, we can add
that as well.

Leave a Reply

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