Wednesday, April 22, 2015

[Laravel] Methods to Custom validation error message

There is 3 methods (i know) to custom the validation message:

Method 1 : 

Change line at views which show the error.
Chnage the line from calling the default message
@if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> @endif
to (change your default error maessage from the red text):
@if ($errors->has('name')) <p class="help-block">Please input your name in the blank.</p> @endif

Method 2 : 

Edit value at validation.php
Laravel 4 path:
app\lang\en\validation.php
Laravel 5 path:
resources\lang\en\validation.php

return array(
    /*
    |--------------------------------------------------------------------------
    | Validation Language Lines
    |--------------------------------------------------------------------------
    |
    | The following language lines contain the default error messages used by
    | the validator class. Some of these rules have multiple versions such
    | as the size rules. Feel free to tweak each of these messages here.
    |
    */

    "accepted"      => "The :attribute must be accepted.",
    "active_url"    => "The :attribute is not a valid URL.",
    "after"         => "The :attribute must be a date after :date.",
    "alpha"         => "The :attribute may only contain letters.",
    "alpha_dash"    => "The :attribute may only contain letters, numbers, and dashes.",
    "alpha_num"     => "The :attribute may only contain letters and numbers.",
    "array"         => "The :attribute must be an array.",
    "before"        => "The :attribute must be a date before :date.",
    "between"       => array(
        "numeric"   => "The :attribute must be between :min and :max.",
        "file"      => "The :attribute must be between :min and :max kilobytes.",
        "string"    => "The :attribute must be between :min and :max characters.",
        "array"     => "The :attribute must have between :min and :max items.",
    )
);

Method 3 : 

make an array and pass to your costumn Error Message to validator class at the route or controller

$rules = array(
    'name'      => 'required',                                   
    'interest'  => 'required|unique:tbl_columnist_article',      
    'content'   => 'required'
);   
$messages = array(
    'name.required'     => 'Please fill in the name.',
    'interest.required' => 'Please select an interest',
    'interest.unique'   => 'SomeOne has this interest, please choose another interest',
    'content.required'  => 'Please fill in the contetnt.'
);      
$validator = Validator::make(Input::all(), $rules, $messages);
And then use foreach to echo message:
@if($errors->has())
   @foreach ($errors->all() as $error)
      <div>{{ $error }}</div>
  @endforeach
@endif

No comments :

Post a Comment