2017-07-04 51 views
0

如果我有一些基本的表單驗證(爲了簡單起見,僅使用empty())並且想要將這些錯誤消息放入一個數組中,我將如何實現這一點?如何在數組中存儲表單驗證錯誤

$errors = array(); 
$response = array(); 

if(empty($_POST['name'])) { 

    $errors['name'] = "Name required"; 
} 

if(empty($_POST['email'])) { 

    $errors['email'] = "Email required"; 
} 

$response['errors'] = $errors; 

if(!empty($errors)) { 

    $response['success'] = false; 
    $response['message'] = "fail"; 

} else { 

    $response['success'] = true; 
    $response['message'] = "<div class='alert alert-success'>Success</div>"; 
} 

echo json_encode($response); 
} 
+2

只需使用一個數組,而不是字符串:'消息[] = 「...」' – Marvin

+0

我看到你正在使用的引導。你在使用PHP框架嗎? –

+0

是的,我正在使用引導程序 – Jonathan

回答

1
$message = []; 

if(empty($_POST['name'])) { 

array_push($message , "Name required <br />"); 

} 

if(empty($_POST['email'])) { 

array_push($message , "Email required <br />"); 

} 

if(!empty($message)) { 
foreach ($message as $str) 
echo "<div class='alert alert-danger'>" . $str . "</div>"; 

} else { 
// success 

} 
+0

道歉,我在最初的問題中更改了代碼 – Jonathan