Validation

The Rhapsody\Core\Validator class provides a simple and powerful way to validate incoming data from forms and API requests. It helps ensure data integrity and provides a clean way to handle errors and user feedback.

Basic Usage

In your controller, you can instantiate the validator, define your rules, and then check if the data passes. If validation fails, you can easily get the error messages and pass them back to the view.

// In a controller method, e.g., handleContact()
use Rhapsody\Core\Validator;

$data = $request->getBody();
$validator = new Validator();

$rules = [
    'name' => 'required|min:2|max:50',
    'email' => 'required|email',
    'password' => 'required|min:8|confirmed',
    'avatar' => 'required|image|mimes:jpeg,png'
];

if ($validator->validate($data, $rules)) {
    // Data is valid, proceed with your logic...
} else {
    // Data is invalid, re-render the form with errors.
    return $this->view('your_form.twig', [
        'errors' => $validator->getErrors(),
        'old' => $data // Pass back the old input
    ]);
}

Displaying Errors in Views

When validation fails, the controller passes an errors object and an old object back to the view. You can use these to repopulate the form and display error messages next to the relevant fields.

<!-- In your Twig template -->
<label for="email">Email</label>
<input type="email" name="email" value=""
       class="">

Available Validation Rules

  • required: The field must not be empty.
  • email: The field must be a valid email address.
  • url: The field must be a valid URL.
  • min:X: The string must be at least X characters long.
  • max:X: The string must not exceed X characters.
  • confirmed: The field must have a matching field named {field}_confirmation (e.g., password and password_confirmation).
  • numeric: The field must be a numeric value.
  • alpha: The field must consist entirely of letters.
  • alpha_num: The field must consist entirely of letters and numbers.
  • date_format:Y-m-d: The field must be a valid date matching the given format.
  • in:foo,bar,...: The field's value must be in the given list.
  • not_in:foo,bar,...: The field's value must not be in the given list.
  • image: The uploaded file must be a valid image (jpg, png, gif, webp).
  • mimes:jpeg,png,...: The uploaded file must have one of the given MIME types/extensions.