Tom Worster wrote:
On 5/6/09 4:02 PM, "Al" <news@xxxxxxxxxxxxx> wrote:
Here's the way I handle validating user form inputs. Each function validates
several things and throws an error with the message stating what's wrong.
try
{
checkEmailAddr($userSubmitedDataArray[EMAIL_ADDR_FIELD]);
checkPhoneDigits($userSubmitedDataArray[PHONE_NUM_FIELD],
'phone');
checkNotes($userSubmitedDataArray, $sizesArray);
if(!empty($userSubmitedDataArray[CELLPHONE_NUM_FIELD]))
{
checkPhoneDigits($userSubmitedDataArray[CELLPHONE_NUM_FIELD],
'cell');
checkCellCarrier($userSubmitedDataArray['carrier']);
}
}
catch (Exception $e)
{
$userErrorMsg = $e->getMessage(); //Message text in check
function
}
A typical function looks like this:
function checkEmailAddr($emailAddr)
{
if(empty($emailAddr))
{
throw new Exception("No email address provided");
}
if(!preg_match("%\w+@%", $emailAddr))
{
throw new Exception("Email address missing mailbox name.");
}
if(!filter_var($emailAddr, FILTER_VALIDATE_EMAIL))
{
throw new Exception("Email address error. Syntax is wrong. ");
}
$domain = substr(strchr($emailAddr, '@'), 1);
if(!checkdnsrr($domain))
{
throw new Exception("Email address warning. Specified domain
\"$domain\" appears to be invalid. Check carefully.");
}
return true;
}
thanks for the example, Al. the combination of checker functions and
exceptions (as far as i understand them, the exceptions chapter of the php
manual is a little terse) so you can throw from inside the checker seems
convenient.
Incidentally, the throw new exception doesn't have to be in a function. it can
be simply in your code sequence. e.g.,
if($foo != 'boo') throw new Exception("foo is not equal to boo. ");
try/catch is a God sent for me. I'm big on telling the user everything that is
wrong with their entry and what to do about it. Prior to try/catch being
available, I'd have to have to test the return for "true" or a message and then
have logic to skip over the following checks to post a message for the user.
Keep in mind, with this approach, it is most useful if you want to inform users
about errors one at a time. If you want to get fancy, you can control the
exception handler. See manual on this.
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php