入力フォームを作っていて、現在コードの検証中です。ブログからこの検証コードに出くわしましたが、かなりきれいに見えます。このコードをフォームに実装する方法を知っている人はいますか? どんな助けでも大歓迎です。
function field_validator($field_descr, $field_data, $field_type, $min_length="", $max_length="", $field_required=1) {
# array for storing error messages
global $messages;
# first, if no data and field is not required, just return now:
if(!$field_data && !$field_required){ return; }
# initialize a flag variable - used to flag whether data is valid or not
$field_ok=false;
# this is the regexp for email validation:
$email_regexp="^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|"
$email_regexp.="(([a-zA-Z0-9-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$";
# a hash array of "types of data" pointing to "regexps" used to validate the data:
$data_types=array(
"email"=>$email_regexp,
"digit"=>"^[0-9]$",
"number"=>"^[0-9]+$",
"alpha"=>"^[a-zA-Z]+$",
"alpha_space"=>"^[a-zA-Z ]+$",
"alphanumeric"=>"^[a-zA-Z0-9]+$",
"alphanumeric_space"=>"^[a-zA-Z0-9 ]+$",
"string"=>""
);
# check for required fields
if ($field_required && empty($field_data)) {
$messages[] = "$field_descr is a required field.";
return;
}
# if field type is a string, no need to check regexp:
if ($field_type == "string") {
$field_ok = true;
} else {
# Check the field data against the regexp pattern:
$field_ok = ereg($data_types[$field_type], $field_data);
}
# if field data is bad, add message:
if (!$field_ok) {
$messages[] = "Please enter a valid $field_descr.";
return;
}
# field data min length checking:
if ($field_ok && $min_length) {
if (strlen($field_data) $max_length) {
$messages[] = "$field_descr is invalid, it should be less than $max_length characters.";
return;
}
}
}