Validation

Sprnva has a built in request validator and it's easy to use.

In order to protect informations to pass through, we need to validate the user's request through a validator and extract and sanitize each request to avoid special characters and converts code to htmlentities.

Request::validate($route, $input_to_validate = []);

$route - Is used to redirect if the validator detects an error in validating the request.

$input_to_validate - An array of input names with a value of the validation types.

Let's look some example of request validations

In views:

<form method="POST" action="<?= route("/register") ?>">
    <?= csrf() ?>
    <div class="form-group">
        <label for="email">E-mail</label>
        <input type="email" class="form-control" name="email" autocomplete="off" autofocus>
    </div>
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" name="name" autocomplete="off">
    </div>
    <div class="form-group">
        <label for="username">Username</label>
        <input type="text" class="form-control" name="username" autocomplete="off">
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" name="password" autocomplete="off">
    </div>

    <div class="d-flex justify-content-end">
        <a href="<?= route("/login"); ?>" style="font-size: 18px;">
            <small id="emailHelp" class="form-text text-muted mb-1">Already registered?</small>
        </a>
        <button type="submit" class="btn btn-secondary btn-sm text-rigth ml-2">REGISTER</button>
    </div>
</form>

In routes:

Route::post("/register", ['RegisterController@store']);

In controller:

<?php

namespace App\Controllers;

class RegisterController
{
    public function store()
    {
        $request = Request::validate('/register', [
            'email' => ['required', 'email'],
            'username' => ['required', 'unique:users'],
            'password' => ['required'],
        ]);
    }
}

Last updated