Validator


Instantiating Validator

The Validator class is typically instantiated in the Controller, particularly in a method that validates requests from HTML form or AJAX.

To instantiate this class using its __construct(), you need to prepare the data and rules.

use Zap\Core\Utils\Validator;
public function registration(Request $request){
$registrationData = $request->all();
$rules = [
 'username' => 'required|min:8',
 'email' => 'required|email'
];
$validator = new Validator($registrationData, $rules);
//rest of the code
}

Alternatively, if the Validator class is injected as a dependency in the method, use the make() method.

use Zap\Core\Utils\Validator;
public function registration(Request $request, Validator $validator){
$registrationData = $request->all();
$rules = [
 'username' => 'required|min:8',
 'email' => 'required|email'
];
$validator::make($registrationData, $rules);
//rest of the code
}

Retrieving Errors

Retrieving validation errors is useful to return error messages to frontend. However, the form fields in the frontend needs to have their "old" values, which can be done this way: value={{ $old['username'] ?? '' }}. This $old variable is of course sent from the controller method.

Assuming that the form action targets the same route with that renders the registration page, the routes may look like this:

Route::get('/registration', 'AccountController@registration')->name('account.registration.');
Route::post('/registration', 'AccountController@registration')->name('account.registration.');

The full controller method, along with errors retrieval, may look like this:

public function registration(Request $request, Validator $validator) {
$data = [
 'assets' => $this->assets->setAssets(source: 'local'),
 '_title' => 'Registration',
 '_description' => "" ,
 '_robots' => 'index, follow',
 '_bodyClass' => 'bg-light',
 'navbar' => 'navbars.home-navbar',
 'footer' => 'footers.home-footer',
];

if(!$request->input('username')) {
 $html = $this->render('account/registration', $data);
 return $this->response($html);
}

$rules = [
 //rules...
];

$validator::make($request->all(), $rules);

if($validator->fails()){
 $data = [
 'errors' => $validator->errors(),
 'old' => $request->all()
 ];
 $html = $this->render('account/registration', $data);
 return $this->response($html);
}else{
 // rest of the logic
}

}

Then, the blade view may look like this:

@extend('layouts.base')
@section('content')

<form method="post" action="{{ route(account.registration) }}">
 <!-- other fields -->
 <input type="text" name="username" value="{{ $old['username'] ?? '' }}"/>
 <span class="d-block text-danger">{{ $errors['username'][0] ?? '' }}</span>
 <input type="email" name="email" value="{{ $old['email'] ?? '' }}"/>
 <span class="d-block text-danger">{{ $errors['email'][0] ?? '' }}</span>
 <!-- other fields -->
</form>

@endsection 
@push(scripts)
@endpush

If you want to check whether a specific field has validation error, uses hasError(string $field). If you want to retrieve the first error message for a given field, use first(string $field), which will return null if no error exists.

Validation Passes

If validation passes or no error exists, all validated fields and their values can be retrieved by using the method validated(). The content it returns can then be processed further (e.g., adding record to database).

public function registration(Request $request, Validator $validator) {
 // existing code 
 $validData = $validator->validated();
 $results = $this->model('AccountModel')->createNewUser($validData);
 // rest of the code
}

Supported Validation Rules

Rules are applied per field by separating them with a vertical bar (|). Parameters are passed following a colon (:).

Rule Parameter Example Description Example Error Message
required N/A Ensures the field is present and not empty/null field is required
email N/A Validates format using FILTER_VALIDATE_EMAIL field must be a valid email
min min:8 Ensures string length is at least the specified minimum. field must be at least 8 characters
max max:255 Ensures the string length does not exceed the specified maximum field must not exceed 255 characters.
numeric N/A Checks whether the value is numeric or a numeric string. field must be numeric.
url N/A Validates URL format using PHP's FILTER_VALIDATE_URL. field must be a valid URL.
boolean N/A Validates strict booleans (true/false) or integer/string equivalents (0, 1, '0', '1'). field must be boolean.
in in:admin,user Ensures the value exists within a comma-separated list of allowed options. field must be one of: admin,user.
array N/A Validates that the input is an array type. field must be an array.
regex regex:/^[a-z0-9_-]+$/i Validates the string value against a custom Regular Expression pattern. field format is invalid.
confirmed N/A Checks if a matching {field}_confirmation exists in the data and equals the field's value. field confirmation does not match.

Use the confirmed rule when the form data has fields like password and password_confirmation. The rule may look like this:

$rules = [
 //other key-value pairs
 'password' => 'required|min:6|confirmed',
 //other key-valye pairs
];

Validator will check the second field with _confirmation and check whether the values are equal.