Validation in Laravel with Example

Validation in Laravel


Laravel Validation is the way through which we can verify and filter the data coming to the Application database. We can have clean and validated data in the database coming with HTTP with powerful validation rule.

As we know that we store the data in the Database using form. As we must not fill our database with junk and invalid data, we do form validation in client Side as well as server side. The validation in laravel purpose is to get the exact data what is required for application.

Route::get('personal-detail/show', 'PersonalController@showForm');
Route::post('personal-detail/save', 'PersonalController@savePersonalData');

Above two route, One route purpose is to show the Personal Detail form other is to save the personal data in the database. While saving the blog data we will validate all the data format and blog post then we will store in database.

Personal Form Code is below:

<body>
<div class="container" style="width:80%; margin-left:10%;margin-right:10%">
  <h2>Validation form</h2><br/>
  
   {!! Form::open(['url'=>'form-validation/save','id'=>'savePostMaster', 'class' => 'formstyle']) !!}
    <div class="form-group">
      <label for="fullname">Full Name:</label>
      {!! Form::text('FULL_NAME','',array('class'=>'form-control ','id'=>'FULL_NAME','placeholder'=>'Enter Your Full Name')) !!}
      <span class="error" style="color:red"> @if($errors->has('FULL_NAME')) {{ $errors->first('FULL_NAME') }} @endif</span>
    </div>
    <div class="form-group">
      <label for="mobile">Mobile Number:</label>
      {!! Form::text('mobile','',array('class'=>'form-control','id'=>'mobilr','placeholder'=>'Enter Mobile Number')) !!}
      <span class="error" style="color:red"> @if($errors->has('mobile')) {{ $errors->first('mobile') }} @endif</span>
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      {!! Form::email('email','',array('class'=>'form-control','id'=>'email','placeholder'=>'Enter Email ID')) !!}
      <span class="error" style="color:red"> @if($errors->has('email')) {{ $errors->first('email') }} @endif</span>     
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  {!!form::close()!!}
</div>

</body>

 O/P of above code.

laravel form validation

We use laravel Validate function to implement the validation rules in the controller, if the validation method fails then it will halt the execution of code further and it will redirect to the form with error message. We will write the validation logic in PersonalController.

Below is the validation code for your reference purpose.

Validation in Laravel Example


public function saveFormVal(Request $request){         $input = Input::all();         // Validation Code Starts Here         $validatedData = $request->validate([             'FULL_NAME' => 'required|max:25',             'mobile' => 'required|digits:10|unique:valid_table,mobile',             'email' => 'required|email|max:255',         ]);              }

If You will see the above validation code we have applied various validation rules to filter the input Data coming through the HTTP Request. Input field named with FULL_NAME, mobile, email all have certain condition. Like these input field can't be NULL, the mobile number cant be duplicate as well as it must have 10 digit and email id format must be maintain.

If any Input field will not satisfy the condition then validation will fail and it will redirect back with validation error message. See the below image for your reference.

Validation Error message
Refer the input field, User tried to insert the mobile number which have 9 digit as well as the email Id format is not maintain. so these data is junk data which don't serve the purpose.

Here Validation comes in picture, It will filter this all type of unwanted data and will not allow them to store in the database.  


To show all the error on the view add below code.

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div> 
@endif

This above code will print all the validation error message in list format. Above Image is the example which you can refer.

If you want to print all the validation message below the respective input field then you must specify with validation first() method. Below code is there for your reference.

{!! Form::open(['url'=>'form-validation/save','id'=>'savePostMaster', 'class' => 'formstyle']) !!}
    
   <div class="form-group">
      <label for="fullname">Full Name:</label>
      {!! Form::text('FULL_NAME','',array('class'=>'form-control ','id'=>'FULL_NAME','placeholder'=>'Enter Your Full Name')) !!}
      <span class="error" style="color:red"> @if($errors->has('FULL_NAME')) {{ $errors->first('FULL_NAME') }} @endif</span>
    </div>

    <div class="form-group">
      <label for="mobile">Mobile Number:</label>
      {!! Form::text('mobile','',array('class'=>'form-control','id'=>'mobilr','placeholder'=>'Enter Mobile Number')) !!}
      <span class="error" style="color:red"> @if($errors->has('mobile')) {{ $errors->first('mobile') }} @endif</span>
    </div>

    <div class="form-group">
      <label for="email">Email:</label>
      {!! Form::email('email','',array('class'=>'form-control','id'=>'email','placeholder'=>'Enter Email ID')) !!}
      <span class="error" style="color:red"> @if($errors->has('email')) {{ $errors->first('email') }} @endif</span>     
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>

  {!!form::close()!!}

In the above code we have specify the validation error code for each input field which will highlight the error if any validation fails. Below is the image for your reference.

Laravel Validation Error
If any input field will not meet the validation requirement then the Error message will be shown below the Input field.










Some validation Rule list which you can apply on the input filed to get the exact user data to serve our purpose.

Laravel Validation Rules


Validation Rule
Purpose
required
Required validation will ensure that input field must not be null.
alpha
Alpha will ensure that input field must have only Alphabetic Character
Alpha_num
Alpha_nun will check that input field will have only alphabet and Numeric as a input.
digits:value
Digits will ensure that the input filed data must have only numeric data with exact digit length.
digits_between:min,max
Digits_between will check that the input data coming through HTTP request must have numeric data only as well as it must contain the digit in between the specified length.
email:value
Email validation rule will check and ensure that proper email format is given which is followed worldwide.
image
Image will ensure that the uploaded file in the form must be in valid image format. Like JPG, PNG, JPEG, SVG, BMP, GIF etc.
integer
This will ensure that input data will have only integer value only.
ip
This will ensure that the entered value for input field must have in IP Format.
min:value
Min validate that the input field data must have minimum digit.
max:value
Max validation rule ensure that input field must not have greater than the specified digit.
not_regex:pattern
This will ensure that the given data must match with given regular expression.
required_if:anotherfield,value,...
This will check based on the other input field. If first input value is there then the next input field is required.
unique:table,column
This will ensure that the entered data must not have the duplicate value in the specified table column.

Validation Code and Rules Example below with Example and Explanation.


'password' => 'required|min:8|confirmed',
'password_confirmation' => 'required',

'PICK_TEXT'=>'required|max:200',

'code'=> 'required|unique:educational_district,code|digits:3',

'STORE_INDEX_SEQUENCE'=>'required|integer',

'file' => 'required|max:204800|mimes:pdf',

'nadid'=>'required|min:9|max:12|unique:ENTRACNEDOCUMENTMST,
DOCUMENTNUMBER,'.Input::get('id').'|confirmed|
regex:/^[A-Z][A-Z0-9.,$;]+$/',

'nadid_confirmation'=>'required|min:9|max:12',

'sms_email' => 'required|not_in:0',                   
'senderid'=>'required_if:sms_email,==,1',
'email_from'=>'required_if:sms_email,==,2',

'status' => 'required',
'remarks' => 'required_if:status,==,0,2,3,5',

'approved_status' => 'required',
'capacity_applied' => 'required|integer',
'capacity_approved' => 'required_if:approved_status,==,1|integer|
lte:capacity_applied',

'remarks' => 'required_if:approved_status,==,0,2,3',

'image' => 'required:max:204800|mimes:jpeg,jpg,bmp,pdf,png'

'class_id' => 'required|not_in:0',

'code'=> 'required|unique:mp_constituencies,code,'.$mp_constituency->id.',id',

'mobile_no'     => 'required|integer|digits:10',

Using Eloquent in Validation 

'email' => 'unique:App\User,email_address'

Create Validators Manually 


If we don't want to use validate() method, then we can create validators manually using validation Facades.We use make() method to create manual validator.
   
use Illuminate\Support\Facades\Validator;

 $validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ]);

        if ($validator->fails()) {
            return redirect('/personal-details')
                        ->withErrors($validator)
                        ->withInput();
        }


Instead of writing url redirection validation code once the validation fails, you can use auto url redirection using validate method. You have to call the instance.

$validator = Validator::make($request->all(), [
            'first_name' => 'required|max:255',
            'mobile' => 'required|digits:10',
        ])->validate();



Laravel Validation Form Example :


<div style="background-color:white">
  <h2>Laravel Form Validation Example</h2>
  <form method="POST" action="/form-validation" autocomplete="off">
    @if(count($errors))
      <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.
        <br/>
        <ul>
          @foreach($errors->all() as $error)
          <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
    @endif
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('firstname') ? 'has-error' : '' }}">
          <label for="firstname">Full Name:</label>
          <input type="text" id="fullname" name="fullname" class="form-control" placeholder="Enter Full Name" value="{{ old('firstname') }}">
          <span class="text-danger">{{ $errors->first('fullname') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('emailid') ? 'has-error' : '' }}">
          <label for="emailid">Email ID:</label>
          <input type="text" id="emailid" name="emailid" class="form-control" placeholder="Enter Email ID" value="{{ old('emailid') }}">
          <span class="text-danger">{{ $errors->first('emailid') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="form-group {{ $errors->has('mobileno') ? 'has-error' : '' }}">
          <label for="mobileno">Mobile No:</label>
          <input type="text" id="mobileno" name="mobileno" class="form-control" placeholder="Enter Mobile No" value="{{ old('mobileno') }}">
          <span class="text-danger">{{ $errors->first('mobileno') }}</span>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6">
        <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
          <label for="password">Password:</label>
          <input type="password" id="password" name="password" class="form-control" placeholder="Enter Password" >
          <span class="text-danger">{{ $errors->first('password') }}</span>
        </div>
      </div>
      <div class="col-md-6">
        <div class="form-group {{ $errors->has('confirmpassword') ? 'has-error' : '' }}">
          <label for="confirmpassword">Confirm Password:</label>
          <input type="password" id="confirmpassword" name="confirmpassword" class="form-control" placeholder="Enter Confirm Passowrd">
          <span class="text-danger">{{ $errors->first('confirmpassword') }}</span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <button class="btn btn-success">Submit</button>
    </div>
  </form>
</div>



Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post