Tips of validation in Laravel 4

Laravel provide a very helpful feature on validation. If you are still writing somethings like this…

if(Input::get("password") != Input::get("password_confirmation")){
     return Redirect::back()->with("error","password confirm is not matched");

I think it is time for you to understand how powerful Laravel is.


Mail, password confirmation can be done easily by validation rules.

$rules = array(
		"password" 				=> "required|confirmed",
		"password_confirmation"	=> "required",

$validator = Validator::make(Input::all(), $rules);
<form action="post">
    <input type="password" name="password">
    <input type="password" name="password_confirmation">

For mail confirmation, replace password_confirmation to email_confirmation.

Unique value

Let’s say, “name_col” must be unique and there is no duplicate.

| id | name_col    |
|  1 | Steve       |
|  2 | John        |
$rules = array(
		"name_col" => required|unique:mytable",

$validator = Validator::make(Input::all(), $rules);

Regular Expression

Another powerful feature in Laravel 4 validation is regular expression. Following sample show the Katagana regular expression.

$rules = array(
		'katagana'      => 'regex:/^[ァ-ヶー]+$/',

$validator = Validator::make(Input::all(), $rules);

Custom Error Message

You would like to have your own error message, open app/lang/en/validation.php and configure. Let’s say, you want to modify “confirmation” error message.

"confirmed" => "Hey! :attribute is not matched", 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s