Exceptions for validation code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
exine
Forum Newbie
Posts: 4
Joined: Wed May 03, 2006 4:11 pm

Exceptions for validation code

Post 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!
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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 :)
exine
Forum Newbie
Posts: 4
Joined: Wed May 03, 2006 4:11 pm

Post 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.
Post Reply