1
\$\begingroup\$

Let's pretend the following:

 <?php
 // Functions to validate/sanitize user input
 function validateUsername() {
    // If accepted, return true, else return false
 }
 function validatePassword() {
    // If accepted, return true, else return false
 }
 function validateEmail() {
    // If accepted, return true, else return false
 }

This is how I handle user input:

// Getting all user input
$values = $_POST['values'];

$error = false;

if (!validateUsername($username) && $error === false) {
    $errorMessage = "Username can't contain special characters";
    $error = true;
}
if (!validatePassword($password) && $error === false) {
    $errorMessage = "Password is'nt secure enought";
    $error = true;
}
if (!validateEmail($email) && $error === false) {
    $errorMessage = "Email is not correctly formatted";
    $error = true;
}

if ($error === true) {
    echo $errorMessage;
} else {

    // Do something

}
?>

But I'm sure there is a better approach. What is the best (or a good) way to handle user input messages/errors?

Also I've read a tutorial (which unfortunately I can't find anymore) where it was recommended to give the users hints and tips about their input, instead of giving them a big bold red warning.

For example to accept not only 1234 AB (Dutch postcodes), but also 1234ab, 1234AB and 1234 ab and let the script convert it to the official notation 1234 AB.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ well, doesn't that depend on what kind of project you're working on? procedural vs oop, using a framework and if so, what framework? \$\endgroup\$
    – chris
    Commented Apr 1, 2016 at 9:23
  • \$\begingroup\$ No framework and procedurial (functional) coding style \$\endgroup\$ Commented Apr 1, 2016 at 9:34

2 Answers 2

1
\$\begingroup\$

May this below class will help you. Put this Valiation class in file named as Validation.php file.

<?php 
/** 
 * This class will provide server side validation for different rules with custom 
 * provided message for respective rule. 
 * 
 * @author: Alankar More. 
 */ 
class Validation 
{ 
    /** 
     * Posted values by the user 
     * 
     * @var array 
     */ 
    protected static $_values; 

    /** 
     * Rules set for validation 
     * 
     * @var array 
     */ 
    protected static $_rules; 

    /** 
     * Error messages 
     * 
     * @var array 
     */ 
    protected static $_messages; 

    /** 
     * To send response 
     * 
     * @var array 
     */ 
    protected static $_response = array(); 

    /** 
     * For storing HTMl objects 
     * 
     * @var array 
     */ 
    protected static $_elements; 

    /** 
     * Html object 
     * 
     * @var string 
     */ 
    protected static $_inputElement; 

    /** 
     * Value of Html object 
     * 
     * @var mixed (string|boolean|integer|double|float) 
     */ 
    protected static $_elementValue; 

    /** 
     * Name of validation rule 
     * 
     * @var string 
     */ 
    protected static $_validationRule; 

    /** 
     * Value of validation rule 
     * 
     * @var mixed (string|boolean|integer|double|float) 
     */ 
    protected static $_ruleValue; 

    /** 
     * Initializing class 
     * 
     * @param array $inputArray 
     * @param array $values 
     */ 
    public static function _initialize(array $inputArray, array $values) { 
        self::$_values = $values; 
        self::$_response = array(); 

        self::generateArrays($inputArray); 
        return self::applyValidation(); 
    } 

    /** 
     * Separating rules and values 
     * 
     * @param array $input 
     */ 
    public static function generateArrays(array $input) { 
        self::$_messages = $input['messages']; 
        self::$_rules = $input['rules']; 
    } 

    /** 
     * Applying validation for the form values 
     * 
     */ 
    public static function applyValidation() { 
        foreach (self::$_rules as $rk => $rv) { 
            $_element = self::$_rules[$rk]; 
            if (is_array($_element)) { 
                foreach ($_element as $key => $ruleValue) { 
                    if (!self::$_elements[$rk]['inValid']) { 
                        $method = "_" . $key; 
                        self::$_inputElement = $rk; 
                        self::$_elementValue = self::$_values[$rk]; 
                        self::$_validationRule = $key; 
                        self::$_ruleValue = $ruleValue; 

                        self::$method(); 
                    } 
                } 
            } 
        } 

        if (count(self::$_response) == 0) { 
            self::$_response['valid'] = true; 
        } 

        return self::$_response; 
    } 

    /** 
     * Method to check wheather the input element holds the value. 
     * If not then assingn message which is set by the user. 
     * 
     */ 
    protected static function _required() { 
        if (self::$_ruleValue) { 
            if (trim(self::$_elementValue) == NULL && 
                strlen(self::$_elementValue) == 0) { 
                self::setErrorMessage("Field Required"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * Maximum length of input 
     * 
     */ 
    protected static function _maxLength() { 
        if (self::$_ruleValue) { 
            if (strlen(trim(self::$_elementValue)) > self::$_ruleValue) { 
                self::setErrorMessage("Enter at most " . self::$_ruleValue . " charachters only"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * Minimum length of input 
     * 
     */ 
    protected static function _minLength() { 
        if (self::$_ruleValue) { 
            if (self::$_ruleValue > strlen(trim(self::$_elementValue))) { 
                self::setErrorMessage("Enter at least " . self::$_ruleValue . " charachters "); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * Allow alphabets only 
     * 
     */ 
    protected static function _number() { 
        if (self::$_ruleValue) { 
            $str = filter_var(trim(self::$_elementValue), FILTER_SANITIZE_NUMBER_INT); 
            if (!preg_match('/[0-9]/', $str)) { 
                self:: setErrorMessage("Enter numbers only"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * Allow alphabets only 
     * 
     */ 
    protected static function _alphabetsOnly() { 
        if (self::$_ruleValue) { 
            $str = filter_var(trim(self::$_elementValue), FILTER_SANITIZE_STRING); 
            if (!preg_match('/[a-zA-z]/', $str)) { 
                self:: setErrorMessage("Enter alphabates only"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * Allow alphabets and numbers only 
     * 
     */ 
    protected static function _alphaNumeric(){ 
        if (self::$_ruleValue) { 
            $str = trim(self::$_elementValue); 
            if (!preg_match('/[a-zA-z0-9]/', $str)) { 
                self:: setErrorMessage("Alphanumeric only"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * To check enter email is valid 
     * 
     */ 
    protected static function _email(){ 
       if (self::$_ruleValue) { 
            $str = filter_var(trim(self::$_elementValue), FILTER_VALIDATE_EMAIL); 
            if (!$str) { 
                self:: setErrorMessage("Enter valid email"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * To check enter url is valid 
     * 
     */ 
    protected static function _url(){ 
       if (self::$_ruleValue) { 
            $str = filter_var(trim(self::$_elementValue), FILTER_VALIDATE_URL); 
            if (!$str) { 
                self:: setErrorMessage("Enter valid URL"); 
                self::setInvalidFlag(true); 
            } else { 
                self::setInvalidFlag(false); 
            } 
        } 
    } 

    /** 
     * Setting invalid flag for every element 
     * 
     * @param boolean $flag 
     */ 
    private static function setInvalidFlag($flag) { 
        self::$_elements[self::$_inputElement]['inValid'] = $flag; 
    } 

    /** 
     * Setting error message for the input element 
     * 
     * @param string $message 
     */ 
    private static function setErrorMessage($message) { 
        if (self::$_messages[self::$_inputElement][self::$_validationRule]) { 
            $message = self::$_messages[self::$_inputElement][self::$_validationRule]; 
        } 
       array_push(self::$_response, ucfirst($message)); 
    } 
} 

You can use this class in your application as below:

<form name="frmTest" id="frmTest" action="" method="POST">
    <input type="text" name="first_name" id="first_name" value = "" />
    <button name="submit" value="Submit" type="submit" >Submit</button>
</form>

<?php
require_once 'validation.php';
// Rules specification.
$rules = array('method' => 'POST',
    'rules' => array('first_name' => array('required' => true)
    ),
    'messages' => array('first_name' => array('required' => 'Please enter first name')
    )
);

$userPostedData = $_POST;
$response = Validation::_initialize($rules, $userPostedData);

// if some error messages are present.
if (!$response['valid']) {
    // it will give you the array with error messages.
    echo "<pre>";
    print_r($response);
} else {
    // all applied validations are passed. You can deal with your submitted information now.
    echo "<pre>";
    print_r($_POST);
}
?> 
\$\endgroup\$
5
  • \$\begingroup\$ Nice! But, why 'url' => true for a first_name? \$\endgroup\$ Commented Apr 4, 2016 at 10:10
  • \$\begingroup\$ Actually it was for demonstration that we can also use the validation for URL. Ah ! but it is not currently useful in the current example I have given. I have remove that. \$\endgroup\$ Commented Apr 4, 2016 at 10:20
  • \$\begingroup\$ Ah okay, then i understand:p very nice class! \$\endgroup\$ Commented Apr 4, 2016 at 10:21
  • \$\begingroup\$ Would you care to explain this class? Why is it important to use a class here? What mistakes dit the OP make? Just posting a class is not very useful for making OP a better coder. Also, why is there a static initialize method? Why not just use a constructor and lose the static stuff. \$\endgroup\$ Commented Apr 6, 2016 at 8:48
  • \$\begingroup\$ Yes you are right , we can use construct. and that would be more better way. I have created class here because you can keep all validations in single class and you can use it according to the rule that you are looking for. \$\endgroup\$ Commented Apr 7, 2016 at 9:06
0
\$\begingroup\$

Parse Error on line 3 (by the way)

You can code it however you want. Think like the user: the user will never see your code and is only interested in his current task (in this case, to create an account). So build you PHP script in a way you are currently understanding because you may have to fix bugs.

But to answer you question:

There are uncountable ways to do what you want to do. For example, you can store functions in arrays and use them with foreach.

<?php

# Functions to validate/sanitize user input
$validate['name'] = function()
{
    echo "checking UserName...<br />\n";
    return true;
};
$validate['password'] = function()
{
    echo "checking Password...<br />\n";
    return true;
};
$validate['mail'] = function()
{
    echo "checking Email...<br />\n";
    return false;
};
$validate['age'] = function()
{
    echo "checking Age...<br />\n";
    return true;
};
$validate['country'] = function()
{
    echo "checking Country...<br />\n";
    return true;
};


# loop for every $validate function
foreach ($validate as $key => $check)
{
    if( $check() ) # $check is the validate function
    {
        # may some code before continuing
    }
    else
    {
        # your big bold red warning
        echo "<h1 style=\"colour:red;\">";
        echo "your $key should be validate";
        echo "</h1>";

        # you can stop the loop with break if you want
        # break;
    }
}

?>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.