I noticed that although the survey help file implies that we check
for valid responses using the type/length/precision parameters, we don't.
We just check that all required responses are present. If I'm wrong about
this, I apologize.
So I decided to write some code to do validation. In my setup, the following function
is called right in handler.php right after we check that all required questions are present.
This is preliminary, but I wanted to get feedback from this group.
Is this valuable? What should I change? Also, what is the intent of
the length/precision params for the *numeric* question type.
I'll submit a patch soon - just want some opinions first.
-moshe
/* {{{ proto string response_validate(int survey_id, int section)
Reads current form variables from HTTP_POST_VARS.
Returns an empty string if all fields are
valid, else returns a message string indicating which
responses need to be changed. */
function response_validate($sid, $section) {
global $HTTP_POST_VARS;
$sql = "
SELECT id, length, precise, content, type_id
FROM question
". survey_select_section_sql($sid,$section) ."
ORDER BY position";
$result = mysql_query($sql);
$invalid = array(); // array of invalid responses
while(list($qid, $length,$precise,$content, $type_id) = mysql_fetch_row($result)) {
switch ($type_id) {
case 2: // textbox
if (isset($HTTP_POST_VARS[$qid]) && strlen($HTTP_POST_VARS[$qid]) > $precise) {
$invalid[$qid] = "Response is too long: $content";
}
break;
case 5: //checkboxes
if (isset($HTTP_POST_VARS[$qid])) {
if (count($HTTP_POST_VARS[$qid]) > $precise) {
$invalid[$qid] = "Too many boxes checked: $content";
}
else if (count($HTTP_POST_VARS[$qid]) < $length) {
$invalid[$qid] = "Too few boxes checked: $content";
}
}
break;
case 9: //date
if (isset($HTTP_POST_VARS[$qid]) && strtotime($HTTP_POST_VARS[$qid])) {
$invalid[$qid] = "Invalid date format. Use this format - <i>10 September 2000</i>: $content";
}
break;
case 10: //numeric
// not sure what the length/precision test is all about.
if (isset($HTTP_POST_VARS[$qid]) && !is_numeric($HTTP_POST_VARS[$qid])) {
$invalid[$qid] = "Invalid number format: $content";
}
break;
}
}
if(count($invalid)) {
// we have some invalid responses
$message = "<br />". _('The following responses are invalid:') ."<br>\n";
while(list($qid,$content)=each($invalid)) {
if($GLOBALS['ESPCONFIG']['DEBUG'])
$message .= "<!-- ${qid} -->";
$message .= "${content}<br>\n";
}
return($message);
}
return('');
}
|