调用函数来验证post array php

时间:2015-02-21 21:29:13

标签: php function email-validation

我试图通过php验证一个post数组,Scenario 2工作,Scenario 1没有 - 当在循环中调用函数时,请帮助

情景1     //尝试在循环中调用函数

<form action="new_signup_form_upload.php" method="POST">
Email 1 <input type = "text" name = "email[newsignup_email1]">
Email 2 <input type = "text" name = "email[newsignup_email2]">
<input type="submit" id= "submit" name= "submit">


function validate_email(){
if ($value == "") {
echo $nameErr =  '<div id = "error_message_div">Name is required</div>';
return false;
}
else{
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = '<div id = "error_message_div">Invalid email format</div>';
return false; 
}
}
}

foreach($_POST[email] as $key => $value){
validate_email();
}

情景2     //这里的不同之处在于我在循环中编写函数

<form action="new_signup_form_upload.php" method="POST">
Email 1 <input type = "text" name = "email[newsignup_email1]">
Email 2 <input type = "text" name = "email[newsignup_email2]">
<input type="submit" id= "submit" name= "submit">

foreach($_POST[email] as $key => $value){

if ($value == "") {
echo $nameErr =  '<div id = "error_message_div">Name is required</div>';
return false;
}
else{
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = '<div id = "error_message_div">Invalid email format</div>';
return false; 
}
}
}

1 个答案:

答案 0 :(得分:0)

函数validate_email没有对外部变量的任何访问权限(真正的全局变量除外)。除了对代码的许多其他异议之外......你应该在你的foreach循环中传递$value

function validate_email($value){
if ($value == "") {
echo $nameErr =  '<div id = "error_message_div">Name is required</div>';
return false;
}
else{
if(!filter_var($value, FILTER_VALIDATE_EMAIL)) {
echo $emailErr = '<div id = "error_message_div">Invalid email format</div>';
return false; 
}
}
}

foreach($_POST[email] as $key => $value){
validate_email($value);
}