Input validation - exceptions or conditionals

  • Thread starter Deleted member 43669
  • Start date
Status
Not open for further replies.
D

Deleted member 43669

Guest
Most web frameworks I've seen handle form validation using exceptions; if the form fields or the whole form don't meet the requirements, an exception is thrown and dealt with (redirect back to the form with errors displayed).

Is this the right way to do it? It seems to me that this should be control flow, and exceptions are lousy for control flow. It should look something like

Code:
errors validate_form(values) {
  errors = []
  if(!is_number(values.age)) {
    errors += MustBeNumeric(age);
  }

  if(!values.foo or !values.bar) {
    errors += FooOrBarMustBePresent();
  }

  return(errors);
}

...

// framework code

handleForm() {
  errors = form.validate_form(values);
  if(errors) {
    redirect_to_form(errors);
  }
  redirect_to_success();
}

Thoughts?
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
I would (within my own domain) chastise anyone using exceptions for recoverable control flow of input validation.

If the invalid data is terminal to the program then throw is just fine.

I would hurt the person responsible for the .Net XML serialiser parsing NaN floating points with an exception. Painfully, with lots of unnecessary breaks.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
koala":23ohcx2m said:
Most web frameworks I've seen handle form validation using exceptions; if the form fields or the whole form don't meet the requirements, an exception is thrown and dealt with (redirect back to the form with errors displayed).
Yes, because failure to validate is a terminal event, no more processing will occur. This is precisely what exceptions are intended for.

The only wrinkle is if the validation framework attempts to report all the validation failures simultaenously, like:
Code:
 errors = []
  if(!is_number(values.age)) {
    errors += MustBeNumeric(age);
  }
Then it shouldn't thrown the exception until they are gathered, and it should use "normal" control flow for gathering the validation failures. But it should definitely toss an exception instead of returning.
 
Status
Not open for further replies.