Sri Lanka NIC number validation with Regex in Laravel : Step-by-Step-Guide | Code Abe Academy

This tutorial will teach you how to add Sri Lanka NIC Number Validation with Regex in Laravel Projects. Let’s do it step by step.



    Go to your project file location, and type cmd in the address bar to open the location in the Command Prompt. Then create a new project using following command.

    Create a new project
    composer create-project laravel/laravel nic-number-validation
  1. Create nic-number-validation.blade.php file
  2. Add Bootstrap CDN
  3. Add Form Container
  4. nic-number-validation.blade.php 
    <section class="min-vh-100 d-flex flex-column align-items-center justify-content-center py-4">
          <div class="container-fluid ">
            <div class="row justify-content-md-center">
                <div class="col-md-10 ">
                    <div class="card px-5 py-3 mt-3 shadow">
    <h1 class="text-info text-center mt-2 mb-4">Sri Lankan NIC Number Validation </h1>
                    </div>
                </div>
            </div>
        </div>
        </section>
    
  5. Add form with Validation
  6. nic-number-validation.blade.php
    <form class="needs-validation" action="" method="POST" novalidate>
                                @csrf
                                <div class="mb-2">
                                    <label for="nicNumber" class="form-label">Your NIC Number</label>
                                    <input type="text" class="form-control" name="nicNumber" id="nicNumber"
                                        placeholder="Enter Your NIC Number" required>
    
                                    <div class="invalid-feedback">
                                        Please Enter Valid NIC Number.
                                    </div>
                                </div>
    
                                <div class="mt-4 mb-2">
                                    <div class="d-grid">
                                        <button class="btn btn-success float-right">Submit</button>
                                    </div>
                                </div>
                            </form>
  7. Add form validation script.
  8. nic-number-validation.blade.php
    <script>
            (function() {
                'use strict'
                var forms = document.querySelectorAll('.needs-validation')
                Array.prototype.slice.call(forms)
                    .forEach(function(form) {
                        form.addEventListener('submit', function(event) {
                            if (!form.checkValidity()) {
                                event.preventDefault()
                                event.stopPropagation()
                            }
    
                            form.classList.add('was-validated')
                        }, false)
                    })
            })()
        </script>
    
  9. Create a route.
  10. Web.php
    Route::get('/', function () {
        return view('nic-number-validation');
    });
    
  11. Add Regex NIC Number validation to form input.
  12. nic-number-validation.blade.php
    pattern="[0-9]{9}[vV]|[0-9]{12}" maxlength="12"
    
  13. Add database to .env file.
  14. .env
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=nic_number_validation_db
    DB_USERNAME=root
    DB_PASSWORD=
    
  15. Craete Mobile Number Table and Model.
  16. php artisan make:model NICNumberValidation -m
    
  17. Craete NIC Number column to Table.
  18. n_i_c_number_validations Table
    $table->string('nicNumber');
    
  19. Create Model.
  20. NICNumberValidation Model
    protected $table = 'n_i_c_number_validations';
        protected $primarykey = 'id';
        protected $fillable = ['id','nicNumber'];
    
  21. Migrate the Table.
  22. php artisan migrate
    
  23. Create NIC Number Controller.
  24. php artisan make:controller NICNumberController
    
  25. Add saveNICNumber route.
  26. web.php
    use App\Http\Controllers\NICNumberController;
    
    Route::post('/saveNICNumber',[NICNumberController::class,'saveNICNumber'])->name('saveNICNumber');
    
  27. Add saveNICNumber function.
  28. NICNumberController
          use App\Models\NICNumberValidation;
    use Illuminate\Support\Facades\Validator;
          
          
          public function saveNICNumber(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'nicNumber' => 'required|string',
            ]);
    
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator)->withInput();
            }
    
            $nicNumberValidation = new NICNumberValidation([
                'nicNumber' => $request->input('nicNumber'),
            ]);
    
    
            $nicNumberValidation->save();
    
            return redirect()->back()->with('success', 'NIC added successful.');
        }
    
  29. Add success message.
  30. nic-number-validation.blade.php
    @if (Session::has('success'))
        <div class="alert alert-success" role="alert">
            {{ Session::get('success') }}
        </div>
        @endif
    


Break Down of the Regex Validation Pattern

  • "[0-9]{9}" - by [0-9] it specifies that any digit from 0 to 9. You can also use \d instead of [0-9]. both of them have same purpose. by {9} it indicates that exactly 9 digits must be matched.
  • "[vV]" - it denoted by there must have a lowercase v or an uppercase V after the early 9 digits.
  • "|" - this is the OR operator in regex. It separates two patterns. So there must have either ([0-9]{9}[vV]) pattern or ([0-9]{12}) pattern.
  • "[0-9]{12}" - by [0-9] it specifies that any digit from 0 to 9. You can also use \d instead of [0-9]. both of them have same purpose. by {12} it indicates that exactly 12 digits must be matched. So there must be have 12 digit number.

Post a Comment

Previous Post Next Post