2017-04-08 142 views
1

我想创建一个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

'$ _POST [“registerBtn”]'不是数组,它将是一个字符串。你的意思是循环'$ _POST'数组吗?如果你还没有,把'error_reporting(E_ALL); ini_set('display_errors',1);'在页面顶部。 – Rasclatt

回答

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])){ 
+0

非常感谢您的回答。该解决方案有效,但为什么我们必须切换$ value和$ keys? – user2896120

+0

因为你所检查的''上$ valArr [$键] empty'''那里$ keys'应该是'index'和'$ value'应该是对指数 –

+0

值那么$值始终是索引值? – user2896120