Page 1 of 1

Exceptions for validation code

Posted: Thu May 04, 2006 9:28 am
by exine
I'm wondering how to do my server side validation. I want to populate a class with data entered in a form. In the code which does this I want to keep track of what fields are not valid and why so I can report this to the user. One option would be for each set accessor in the class to return a string with the error if it's invalid. I could also have a validate method in the class which could throw an exception with a list of validation problems.
I'm not sure whether using exceptions for validation is a great idea because it's an expected and common error which could maybe be handled in a better way. Also, if PHP is anything like C# exceptions come with a performance hit.
Anyone have any comments on these approaches or can maybe suggest a suitable pattern?

Cheers!

Posted: Thu May 04, 2006 9:39 am
by Weirdan
Well, I wouldn't use exceptions for fields validation... getting invalid data from a user is not an exception... getting valid data is :)

Posted: Thu May 04, 2006 9:48 am
by exine
haha yeah you're right! I've just realised that a validation method could just return an array of errors, there's no need for an exception.