Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should exceptions be used for form validation?

This might be a n00bish question, but whatever. Is okay to use exceptions for form validation? Let's say I have a form which asks users for their name and email, is right to do the following?

try {
    if (empty($_POST["name"])) {
        throw new UserRegistrationException("Your name cannot be empty.");
    }

    if (filter_var($_POST["email"])) {
        throw new UserRegistrationException("Invalid email");
    }

    // Save new user into database
} catch (UserRegistrationException $e) {
    // Show errors on screen
}

Also -if this is in fact the correct way to do it- if the user submits both an empty name and an invalid email, would both of the exceptions execute or only the one that appears first (the name one in this case)?

I'm using PHP by the way.

like image 697
federico-t Avatar asked Apr 02 '12 02:04

federico-t


1 Answers

I personally like to use exceptions for anything that should stop or alter program flow. In other words, if validation of a particular field changes how data is processed, or requires the process to be repeated, then I always use exception for error handling.

If it's trivial, or I'm simply compiling a list of error messages, then I do not trigger exceptions.

To answer questions, two exceptions cannot be thrown at the same time. The first throw statement that is reached will be thrown. That's not to say that sometimes it doesn't make sense to rethrow as another type of exception.

like image 193
Nilpo Avatar answered Oct 16 '22 19:10

Nilpo