Re: speaking of control structures...
| From: | Al | Date: | Wed, 06 May 2009 20:02:13 +0000 |
| Subject: | Re: speaking of control structures... | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-292360@lists.php.net to get a copy of this message | ||
Tom Worster wrote:
there's a control structure i wish php had: a simple block that you can break out of, e.g. block { if ( condition )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. trybreak;blah... blah... if ( another condition )break;blah... blah... etc... } the block is just like a loop except that it is executed once only. this would be a handy structure for writing input validation code. the blah blah fragments can be used for opening files, talking to the db, manipulating strings, processing dates and times, etc., the conditions for testing if the input is unacceptable. i'm sure many of the programmers here do this kind of thing routinely and have their own habits and solutions. i'd be curious what they are. please let us know! i guess i ought to go first. it's fugly but it works: $once = true; while ( $once ) { $once = false; stuff using break where needed ... } tom
{
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;
}