从数组中显示表单错误消息

时间:2012-05-07 23:55:10

标签: php ajax

我想将GUMP https://github.com/Wixel/GUMP合并到我的网站中以进行服务器端验证。但遗憾的是文档很少,我是PHP的新手。

这是我的验证码:

//Validation
$gump = new GUMP(); 
$rules = array(
    'dept'     => 'required|numeric',
    'hosp'     => 'required|numeric',
    'subhosp'  => 'required|numeric',
    'user'     => 'required|numeric',
    'gpo'      => 'required|boolean|exact_len,1',
    'clin'     => 'required|valid_name',
    'clinmail' => 'required|valid_email',
    'comp'     => 'required|alpha_dash',
    'cpt'      => 'required|alpha_dash',
    'past'     => 'required|boolean|exact_len,1',
    'latex'    => 'required|boolean|exact_len,1',   
);
$validated = $gump->validate($_POST,$rules);
print_r($validated); // Something went wrong

当我在FireBug中查看我的AJAX响应时,上面代码的输出给出了一个类似的数组:

Array
(
    [0] => Array
        (
            [field] => clin
            [value] => .-0
            [rule] => validate_valid_name
        )

    [1] => Array
        (
            [field] => clinmail
            [value] => %$sd
            [rule] => validate_valid_email
        )

)

我需要的是这样的事情:

<div class="error-msg">You did not enter a valid email address</div><br>
<div class="error-msg">You did not enter a valid username</div><br>

从我得到的文件中:

    if($validated === TRUE)
{
    // Do something, everything went well
}
else
{   
    // This is where I am stuck. Do I have to loop through and put my <div> tags here?
}

我的问题是社区如何使用此类处理输出错误消息?我唯一的想法是我循环上面的结果并输出不同的消息,具体取决于字段和破坏的规则,但这似乎很乏味。是否有更好的方法或更好的类来使用独立的PHP输入验证?我正在使用另一个非常容易使用的类,但是当我从内联PHP转移到AJAX时,它开始破坏。

3 个答案:

答案 0 :(得分:4)

将您的代码编辑为:

$gump = new GUMP(); 
$rules = array(
'dept'     => 'required|numeric',
'hosp'     => 'required|numeric',
'subhosp'  => 'required|numeric',
'user'     => 'required|numeric',
'gpo'      => 'required|boolean|exact_len,1',
'clin'     => 'required|valid_name',
'clinmail' => 'required|valid_email',
'comp'     => 'required|alpha_dash',
'cpt'      => 'required|alpha_dash',
'past'     => 'required|boolean|exact_len,1',
'latex'    => 'required|boolean|exact_len,1',   
);

$error_texts = array(
'dept'     => 'You must enter a numeric value',
'hosp'     => 'You must enter a numeric value',
'subhosp'  => 'You must enter a numeric value',
'user'     => 'You must enter a numeric value',
'gpo'      => 'You must enter a boolean value',
'clin'     => 'You must enter a valid name',
'clinmail' => 'You must enter a valid email',
'comp'     => 'You must enter a valid alpha dash',
'cpt'      => 'You must enter a valid alpha dash',
'past'     => 'You must enter 1 char',
'latex'    => 'You must enter 1 char',
);

$validated = $gump->validate($_POST,$rules);

if($validated === TRUE)
{
   echo "Every thing is ok";
}
else
{
    foreach($validated as $key=>$error)
    {
        echo '<div class="error-msg">' . $error_texts["{$error['field']}"] . '</div><br />';
    }
}

答案 1 :(得分:1)

我想补充一点,如果验证失败了两次,例如,如果需要一个值并且必须存在超过10个字符,则@semsems answer将为同一字段打印多行。

我更改了上面的代码并添加了:

$_validated = array();
foreach($validated as $key=>$error)
{
    if ( !in_array($error['field'], $_validated) )
    {
        print '<div class="error-msg">' . $error_texts["{$error['field']}"] . '</div>';
        $_validated[] = $error['field'];
    }
}

答案 2 :(得分:1)

我知道这个问题已有一年的历史并得到了回答,但由于我基于接受的答案并且在我看来使它更好(完全通用的语言环境),我认为分享会很好并获得一些反馈......你们对我的代码有什么看法?现在基于 semsem的答案......我喜欢他编写部分内容的方式,我从中得出以下代码:
首先我用自己的类扩展了GUMP,这样我就可以覆盖一些函数

<?php

require("gump.class.php");

class GumpValidator extends GUMP 
{
    private $locale;
    private $translator;

    public function GumpValidator($lang = "en")
    {
        $this->locale = $lang;
        $this->loadValidationLocales();
    }

    /** Overwrite the default validate() function of GUMP so that I can add an extra "message" property */
    public function validate(array $input, array $ruleset) 
    {
        $validated_data = GUMP::validate($input, $ruleset);
        if(is_array($validated_data)) {
            foreach($validated_data as $index=>$error) {
                $validation = str_replace(":attribute",  $error['field'], $this->translator[$error['rule']]);
                $validation = str_replace(":param",  $error['param'], $validation);
                $validated_data[$index++]['message'] = $validation;
            }
        }


        return $validated_data;
    }

    /** Depending on the language locale, load the proper set of validation messages */
    private function loadValidationLocales()
    {
        $this->translator = require "/lang/" . $this->locale . "/validation.php";
        return $this->translator;
    }  
} // EOC

然后从扩展类中可以看到,我创建了一组用于验证的语言环境消息,我直接从Github上的GUMP代码获取了可能的验证错误的完整列表,看一下函数{{ 1}}获取完整的错误列表。 Github链接here ...我创建的语言环境保存在单独的语言文件夹get_readable_errors()/lang/en/validation.php等...您可以轻松创建任意多个...我从Laravel框架中获取了这个概念...这些/lang/fr/validation.php文件看起来像这样(每个语言/区域设置1个文件),这里是英文版:

validation.php

然后终于在我的POST中验证代码我只是这样称呼它:

<?php

return array(
    "validate_alpha"            => "The :attribute may only contain letters.",
    "validate_alpha_numeric"    => "The :attribute may only contain letters and numbers.",
    .....
);

所以最后我在// load my extended class with language locale I want to use $gump = new GumpValidator("en"); // now validate the data $validated_data = $gump->validate( $_POST, $rules ); 对象中获得message的额外属性,返回时选择了我选择显示错误消息的语言环境...并且瞧!在我的情况下,我在javascript中读取代码以显示$validated_data中的错误,但如果你想要PHP,你也可以查看semsem的答案。所以最后,我知道它需要更多代码,因为我有一个额外的类来包装它和额外的语言环境,但是首先让它通用(每个验证错误)并且第二个容易拥有多种语言环境语言并不甜蜜?