dtqqq24248
dtqqq24248
2012-05-07 23:55

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

已采纳

I wanted to incorporate GUMP https://github.com/Wixel/GUMP into my site for server side validation. But unfortunately the documentation is light and I am new to PHP.

Here is my validation code:

//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

The output from the above code gives me an array like so when I am looking at my AJAX response in FireBug:

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

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

)

And I what I need is something like so:

<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>

From the documentation I get:

    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?
}

My question is how would the community handle outputting error messages with this class? My only thought is that I loop through the results above and output different messages depending on the field and the rule that was broken but that seems tedious. Is there a better way or a better class to use that does standalone PHP input validation? I was using another very easy to use class but it started breaking when I moved away from inline PHP to AJAX.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doudinghan8319 doudinghan8319 9年前

    edit your code to:

    $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 />';
        }
    }
    
    点赞 评论 复制链接分享
  • douqianke7467 douqianke7467 7年前

    I know this question is a year old and been answered, but since I based myself on the accepted answer and in my view made it a sweet better (completely generic with locale as extra), I thought it would be nice to share and get some feedback... what do you guys think about my code? Now based on semsem's answer... I like the way he coded part of it and I derived from it to come up with the following code:
    First I extended GUMP with my own class so I could overwrite some functions

    <?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
    

    Then as you can see from the extended class, I created myself a set of locale language message for validation and I took the full list of possible validation errors directly from the GUMP code on Github, take a look at the function get_readable_errors() to get the full list of errors. Github link here... The locales which I created are saved under separate language folders /lang/en/validation.php, /lang/fr/validation.php, etc... You can easily create as many as you want... I took the concept from Laravel Framework... These validation.php files looks for example, like this (1 file per language/locale), here is the English one:

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

    Then finally in my POST to validate code I just call it like this:

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

    So at the end I get the extra property of message inside the $validated_data object returned with the option of whichever locale language I chose to display the error message...and voilà!!! In my case I read the code in javascript to display the errors in Bootstrap alert, but if you want PHP you can look at semsem answer as well. So at the end, I know it takes more code since I have an extra class to wrap it and extra locales, but isn't sweet to first have it generic (per validation errors) and second to have multiple locale language easily?

    点赞 评论 复制链接分享
  • douzhicui2209 douzhicui2209 9年前

    I would like to add that if a validation fails twice, for example if a value is required and has to exist out of more than 10 characters then @semsems answer would print multiple lines for the same field.

    I changed the above code and added:

    $_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'];
        }
    }
    
    点赞 评论 复制链接分享