我正在尝试创建一个PHP面向对象的表单验证脚本,但我遇到了一个问题。每当我检查我的字段是否为空时,脚本总是会返回消息,说明它们是,即使我的字段在提交时不是空的。我不明白我做错了什么。这是我的代码:
HTML
<form action='' method='POST'>
<label>Full Name</label>
<input type='text' placeholder='Full Name*' name='name'>
<label>Email</label>
<input type='email' placeholder='Email*' name='email'>
<label>Password</label>
<input type='password' placeholder='Password*' name='password'>
<input type='submit' value='Sign Up!' name='registerBtn'>
</form>";
PHP
<?php
class CreateUser
{
/*Declare variables*/
public $errors;
public function __construct(){
/*Initialize array of errors*/
$this->errors = array("empty_err"=>"");
}
/*Function that checks if fields are empty*/
public function checkEmpty($valArr){
foreach ((array)$valArr as $value=>$keys){
if (empty($valArr[$keys])){
$this->errors["empty_err"] = "All fields are required.";
}
}
}
}
$user = new CreateUser();
if (isset($_POST["registerBtn"])){
$user->checkEmpty($_POST["registerBtn"]);
}
?>
答案 0 :(得分:1)
<强> 1。首先改变
将其更改为:
$user->checkEmpty($_POST["registerBtn"]);
的此:强>
$user->checkEmpty($_POST);
<强> 2。第二次更改
将其更改为:
foreach ((array)$valArr as $value=>$keys){
if (empty($valArr[$keys])){
的此:强>
foreach ((array)$valArr as $keys => $value){
if (empty($valArr[$keys])){