Laravel Form Validation- Server Side form validation
Whenever a user submits a form, the input must be validated to ensure that our app is working on clean and useful data. Validating form data prevents user from entering invalid data. For example- if a user is asked to enter their Email address and if the user enters it in wrong format, then we can prevent them and can ask to re-enter the Email id in correct format. Similarly, we can validate form data for required fields, numeric data, max characters etc using laravel validation.
Laravel provides a powerful validation features that enable us to easily validate our form data. If the data is not valid it automatically redirects to the previous location with errors. Let's see how laravel validation works.
Laravel Form Validation- A Quick Example
Let's have a very simple example of how laravel validation works.
Here, I am going to create a sign-up form to create a new user account.
Defining Routes
Route::get('register', function(){ return view('register'); }); Route::post('register', 'UserController@register');
Creating Registration Form
For this, first we need to create a view that contains the register form. Here, I've created a view named register and created a form inside this. I am using bootstrap for designing the form.
You can learn about Laravel Views here.
<!DOCTYPE html> <html> <head> <title>Take Appointment Online</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <form class="form-horizontal"> <fieldset> <!-- Form Name --> <legend>Fill the form to Register</legend> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="name">Name</label> <div class="col-md-4"> <input id="name" name="name" type="text" placeholder="Your Full Name" class="form-control input-md"> </div> </div> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="email">Email</label> <div class="col-md-4"> <input id="email" name="email" type="text" placeholder="someone@example.com" class="form-control input-md"> </div> </div> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" for="mobile">Mobile</label> <div class="col-md-4"> <input id="mobile" name="mobile" type="text" placeholder="+91" class="form-control input-md"> </div> </div> <!-- Multiple Radios (inline) --> <div class="form-group"> <label class="col-md-4 control-label" for="gender">Gender</label> <div class="col-md-4"> <label class="radio-inline" for="gender-0"> <input type="radio" name="gender" id="gender-0" value="Male"> Male </label> <label class="radio-inline" for="gender-1"> <input type="radio" name="gender" id="gender-1" value="Female"> Female </label> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="password">Password</label> <div class="col-md-4"> <input id="password" name="password" type="password" placeholder="Password" class="form-control input-md"> </div> </div> <!-- Password input--> <div class="form-group"> <label class="col-md-4 control-label" for="corfirm">Confirm Password</label> <div class="col-md-4"> <input id="corfirm" name="corfirm" type="password" placeholder="Confirm Password" class="form-control input-md"> </div> </div> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label" for=""></label> <div class="col-md-4"> <input type="submit" class="btn btn-success" value="Register"> </div> </div> </fieldset> </form> </body> </html>
Creating the Controller
You all know how to create controller, if not you can prefer reading HTTP Controllers- Laravel Controllers Tutorial.
Here, we need to create a controller to store the form data into our database.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class UserController extends Controller { // public function register(Request $req){ $user = new \App\User; $user->name = $req->name; $user->email= $req->email; $user->mobile = $req->mobile; $user->gender = $req->gender; $user->password = $req->password; $user->save(); echo "User Created Successfully"; } }
When you execute this project the data entered into the form will be saved to corresponding model. However the data may contain something that is not useful for our app.
Writing Validation Logic
For validating the form data validate method is used. The validate method accepts the incoming HTTP request and a set of validation rules. If there is no error into our input data the following code will execute normally, however in case of any error a redirect response will be generated and will be automatically sent back to the user.
Here we can apply different validation logic for different form elements. So, our updated controller class will be like this.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class UserController extends Controller { // public function register(Request $req){ $this->validate($req, [ 'name' => 'required', 'email' => 'required|email', 'mobile' => 'required|max:10|min:10', 'gender' => 'required', 'password' => 'required|confirmed', 'password_confirmation' => 'required', ]); $user = new \App\User; $user->name = $req->name; $user->email= $req->email; $user->mobile = $req->mobile; $user->gender = $req->gender; $user->password = $req->password; $user->save(); echo "User Created Successfully"; } }
Here, I've used the following validation logics
- required- Field under this validation must be present and should not be empty. A field is said to be empty, if it contains null, empty string, empty array or uploaded file having no path.
- email- Checks for an valid email address having correct format of an email address.
- max- The number of characters in the field should be less than or equal to the given value.
- min- The number of characters in the field should be greater than or equal to the given value.
- confirmed- It matches the value of two inputs. This field should have a matching confirmation field for matching. For example for a password validator field, there should be a password_confirmation field.
Displaying the Errors
As we already have discussed that laravel automatically redirects the user to the previous location in case of validation fails. Here we even don't need to explicitly bind the errors to our get route. All the validation errors will be flashed to the session while redirecting to the previous location. We can check for available errors and then can print all the errors. The error are stored in $errors variable.
@if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif
Laravel Form Validation- AJAX Request and Validation Example
Nowadays most of web applications uses ajax request. In case of ajax request, Laravel does not redirects to the previous location, but generates a json response that we can print to our view using js.
We can make an ajax call and can print all errors (in case of validation error) like this.
$("#form-id").submit(function(e){ e.preventDefault(); $.ajax({ url: "url", type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, success: function(data){ //do something on success }, error: function(data){ var errors = data.responseJSON; for(i in errors){ $("#div-id").append('<p>'+errors[i]+'</p>'); } } }); });
There are a number of validation rules are available for Laravel form Validation.
Click to see all validation rules
How To Insert Password And Confirm Password Using Ajax In Laravel
ReplyDeleteUsing Ajax is another way to insert Passsword with Json request in Laravel. Here you can see, we are using controller, model and send response to ajax via Json..
For More Info:- How To Insert Password And Confirm Password Using Ajax In Laravel