How to Validate Form Input Field using Alpha Rule in Laravel 10

Last Updated on by in Laravel

In this article, you will learn how to create alpha form validation in Laravel application using alpha form validation rule and Bootstrap CSS library.

Alpha refers to the field under validation, and it should be utterly alphabetic characters. Alphabetic characters are the traditional characters of the alphabet used to illustrate speech.

Laravel is a great framework that offers many modules and tools to help you build a web application. Likewise, Laravel offers proper form validation rules that help you set various validation conditions in laravel forms.

For the demonstration, we will create a basic responsive form using the latest version of Bootstrap CSS framework in laravel. We will build a laravel app and create a model and controller to manage the laravel alpha from validation.

The ready-made Bootstrap UI components will help us show the proper alpha validation success and error response in laravel.

Laravel 10 Alpha Form Validation Example

  • Build Laravel Application
  • Connect to Database
  • Set Up Model and Migrations
  • Build Form Validation Controller with Alpha
  • Configure View Template
  • Create New Routes
  • Run Laravel Server

Build Laravel Application

To begin with this tutorial, you must have a code editor, terminal app and a composer tool installed and properly configured.

Open the console screen, type the suggested command, and press enter to invoke the command.

composer create-project laravel/laravel --prefer-dist laravel-demo

Next, enter inside the project directory.

cd laravel-demo

Connect to Database

Now, we have to connect the laravel app with the database. You can do it very quickly; just open the .env file and add your database credentials to the file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

For macOS MAMP PHP server; make sure to additionally include UNIX_SOCKET and DB_SOCKET right below the database details in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Set Up Model and Migrations

In order to store the form value after the form submission, we need to create a model relative to its form value.

php artisan make:model Form -m

Next, a new database/migrations/timestamp_create_forms_table.php file generated you have to go there and define the given code.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('forms', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('forms');
    }
};

Head over to app/Models/Form.php file and make sure to define the ‘name’, property in the $fillable array.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Form extends Model
{
    use HasFactory;
    public $fillable = [
        'name'
    ];    
}

You are now ready to run the migrations.

php artisan migrate

Build Form Validation Controller with Alpha

We need to generate a new controller, go ahead and execute the following command.

php artisan make:controller FormController

After executing the above command; a new file is generated. Make sure to open the app/Http/Controllers/FormController.php file and add the given code into the file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Form;

class FormController extends Controller
{
  public function index() {
    return view('home');
  }

  public function alphaForm(Request $request) {

      $this->validate($request, [
          'name' => 'required|alpha',
       ]);

      //  Save value in database
      Form::create($request->all());
      return back()->with('success', 'Form successfully submitted.');
  }
}

Configure View Template

Enter into the resources/views/ directory; here you have to create a new file.

Ensure that you name it home.blade.php and insert given code into the file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <title>Laravel</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
</head>

<body>
    <div class="container mt-5">

       <h2 class="mb-4">Laravel Alpha Validation Rule Examle</h2>

        @if(Session::has('success'))
            <div class="alert alert-success text-center">
                {{Session::get('success')}}
            </div>
        @endif    

        <form  method="post" action="{{ route('alpha-validate.form') }}" novalidate>

            @csrf

            <div class="form-group mb-2">
                <label>Name</label>
                <input type="text" class="form-control @error('name') is-invalid @enderror" name="name" id="name">

                @error('name')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>

            <div class="d-grid mt-3">
              <input type="submit" name="send" value="Submit" class="btn btn-danger btn-block">
            </div>
        </form>
    </div>
</body>

</html>

Create New Routes

Next, we will be building two new routes one for requesting a controller for opening the view template on the browser and another for validating the input.

Make sure to add given code into the routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FormController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [FormController::class, 'index']);
Route::post('/validate-form', [FormController::class, 'alphaForm'])->name('alpha-validate.form');

Run Laravel Server

We have reached to the last step of our guide; now we need to run the laravel app.

Run the command to evoke the server.

php artisan serve

Test your app by opening the app on the browser with given link.

http://127.0.0.1:8000

How to Validate Form Input Field using Alpha Rule in Laravel

Conclusion

In this step-by-step guide, we have seen the steps that will help us implement alpha validation to the laravel form.

The laravel alpha validation example is used to allow only alpha (alphabetic) characters in the laravel form fields.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.