chrizonline
chrizonline

Reputation: 4979

php form validation - the better way?

i've been doing form submission and validationss. i have been writing long codes to pass data from the controller/php page to a validation class and then pass it back to be displayed on the view.

for instance: controller

if (isset($_POST["btnSubmit")) {
    $result = ClassSomething::validateForm($_POST);
    if (!$result) { //no error
       ClassSomething::insertRecord(...);
    } else {
       $error = $result;
    }

}

class ClassSomething {
    public function validateForm($str) {
        if ($str == "") {
            return "error messagesss";
        }
    }
}

and somewhere in the html, i would display $error

is there a better way to do validation in php?? is there validation codes which can be reuse rather then doing it for every form??

tks in adv.

Upvotes: 2

Views: 485

Answers (1)

Chvanikoff
Chvanikoff

Reputation: 1329

How can I validate POST data for user login form with this class in Kohana:

$post = Validate::factory($_POST)
    ->rules('login', array(
        'not_empty',
        'alpha_dash',
        'min_length' => array(3),
        'max_length' => array(32)
    ))
    ->rules('password', array(
        'not_empty',
        'min_length' => array(4),
        'max_length' => array(64)
    ));

if ($post->check())
{
    // Proceed login
}
else
{
    // $errors will contain an array of errors. If _POST array was empty - $errors will be an empty array.
    $errors = $post->errors('');
}

Upvotes: 3

Related Questions