代码之家  ›  专栏  ›  技术社区  ›  Sebastian

调用函数以验证后置数组php

  •  0
  • Sebastian  · 技术社区  · 9 年前

    我正在尝试用php验证后置数组,场景2有效,场景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 回复  |  直到 9 年前
        1
  •  0
  •   Poul Kruijt    9 年前

    validateemail函数不能访问外部变量(真正全局的变量除外)。除了许多其他对该准则的反对意见。。你应该通过 $value 在你的foreach循环中

    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);
    }