Ignore:
Timestamp:
Jun 4, 2006 8:34:32 AM (18 years ago)
Author:
scdev
Message:

Q - Added lib/Validator.inc.php as a backend to FormValidator? and also to be used directly for non-form validation and assertion.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/lib/FormValidator.inc.php

    r141 r144  
    77 * http requests and displaying errors.
    88 *
     9 * @requires  codebase/lib/Validator.inc.php
    910 * @author    Quinn Comendant <quinn@strangecode.com>
    1011 * @version   1.8
     
    1617$fv = new FormValidator();
    1718
    18 $fv->isEmpty('field_name', sprintf(_("%s cannot be blank."), _("Field name")));
     19$fv->empty('field_name', sprintf(_("%s cannot be blank."), _("Field name")));
    1920$fv->stringLength('field_name', 0, 255, sprintf(_("%s must be %f-to-%f characters in length."), _("Field name"), 0, 255));
    2021$fv->isInteger('field_name', sprintf(_("%s must be an integer."), _("Field name")));
     
    3233---------------------------------------------------------------------
    3334 */
    34 class FormValidator {
     35
     36// Credit card types are defined in class Validator.
     37
     38require_once 'codebase/lib/Validator.inc.php';
     39
     40class FormValidator extends Validator {
    3541
    3642    // Array filling with error messages.
    3743    var $errors = array();
    3844   
    39     // Default error marker;
    40     var $marker = ' class="sc-msg-error"';
     45    // Default error marker.
     46    var $marker = 'sc-msg-error';
    4147
    4248    /**
     
    9096            }
    9197            return false;
    92         }
    93         return (sizeof($this->errors) > 0);
     98        } else {
     99            return (sizeof($this->errors) > 0);           
     100        }
    94101    }
    95102
     
    163170
    164171    /**
    165      * Check whether input has a value. To be used when a value must be empty
    166      * under certain circumstances.
     172     * Ensure the length of string is non-zero.
    167173     *
    168174     * @param  string $form_name the name of the incoming form variable
     
    173179    function notEmpty($form_name, $msg='')
    174180    {
    175 
    176         $val = trim(getFormData($form_name));
    177         if ($val != '') {
    178             $this->addError($form_name, $msg);
    179             return true;
    180         } else {
    181             return false;
    182         }
    183     }
    184 
    185     /**
    186      * Check whether input is blank.
    187      *
    188      * @param  string $form_name the name of the incoming form variable
    189      * @param  string $msg       the message to display on error
    190      *
    191      * @return bool   true if form is empty, false otherwise.
    192      */
     181        if (parent::notEmpty(getFormData($form_name))) {
     182            return true;
     183        } else {
     184            $this->addError($form_name, $msg);
     185            return false;
     186        }
     187    }
     188   
     189    /*
     190    * We were using the isEmpty method *wrong* all these years and should have been using notEmpty.
     191    * But the fact is the only use is to ensure a value is not empty, so this function simply becomes
     192    * an alias of the one-true notEmpty() function.
     193    * @since    03 Jun 2006 22:56:46
     194    */
    193195    function isEmpty($form_name, $msg='')
    194196    {
    195 
    196         $val = trim(getFormData($form_name));
    197         if ($val == '') {
    198             $this->addError($form_name, $msg);
    199             return true;
    200         } else {
    201             return false;
    202         }
     197        $this->notEmpty($form_name, $msg='');
    203198    }
    204199
     
    213208    function isString($form_name, $msg='')
    214209    {
    215         $val = getFormData($form_name);
    216         if (!is_string($val) && $val != '') {
    217             $this->addError($form_name, $msg);
    218             return false;
    219         } else {
    220             return true;
     210        if (parent::isString(getFormData($form_name))) {
     211            return true;
     212        } else {
     213            $this->addError($form_name, $msg);
     214            return false;
    221215        }
    222216    }
     
    232226    function isNumber($form_name, $msg='')
    233227    {
    234         $val = getFormData($form_name);
    235         if (!is_numeric($val) && $val != '') {
    236             $this->addError($form_name, $msg);
    237             return false;
    238         } else {
    239             return true;
     228        if (parent::isNumber(getFormData($form_name))) {
     229            return true;
     230        } else {
     231            $this->addError($form_name, $msg);
     232            return false;
    240233        }
    241234    }
     
    252245    function isInteger($form_name, $msg='', $negative_ok=false)
    253246    {
    254         $val = getFormData($form_name);
    255         $pattern = $negative_ok ? '/^-?[[:digit:]]+$/' : '/^[[:digit:]]+$/';
    256         if ((!is_numeric($val) || !preg_match($pattern, $val)) && $val != '') {
    257             $this->addError($form_name, $msg);
    258             return false;
    259         } else {
    260             return true;
     247        if (parent::isInteger(getFormData($form_name), $negative_ok)) {
     248            return true;
     249        } else {
     250            $this->addError($form_name, $msg);
     251            return false;
    261252        }
    262253    }
     
    274265    function isFloat($form_name, $msg='', $negative_ok=false)
    275266    {
    276         $val = getFormData($form_name);
    277         $pattern = $negative_ok ? '/^-?[[:digit:]]*(?:\.?[[:digit:]]+)$/' : '/^[[:digit:]]*(?:\.?[[:digit:]]+)$/';
    278         if ((!is_numeric($val) || !preg_match($pattern, $val)) && $val != '') {
    279             $this->addError($form_name, $msg);
    280             return false;
    281         } else {
    282             return true;
     267        if (parent::isFloat(getFormData($form_name), $negative_ok)) {
     268            return true;
     269        } else {
     270            $this->addError($form_name, $msg);
     271            return false;
    283272        }
    284273    }
     
    294283    function isArray($form_name, $msg='')
    295284    {
    296         $val = getFormData($form_name);
    297         if (!is_array($val) && !empty($val)) {
    298             $this->addError($form_name, $msg);
    299             return false;
    300         } else {
    301             return true;
     285        if (parent::isArray(getFormData($form_name))) {
     286            return true;
     287        } else {
     288            $this->addError($form_name, $msg);
     289            return false;
    302290        }
    303291    }
     
    309297     * @param  string $form_name the name of the incoming form variable
    310298     * @param  int    $regex     perl regex that the string must match
    311      * @param  bool   $not       set to false to be valid if match, or true
     299     * @param  bool   $valid_on_match       set to false to be valid if match, or true
    312300     *                           to be valid on no match
    313301     * @param  string $msg       the message to display on error
     
    315303     * @return bool   true if value passes regex test
    316304     */
    317     function checkRegex($form_name, $regex, $not, $msg='')
    318     {
    319         $val = getFormData($form_name);
    320         if ($not) {
    321             if (!preg_match($regex, $val))  {
    322                 $this->addError($form_name, $msg);
    323                 return false;
    324             } else {
    325                 return true;
    326             }
    327         } else {
    328             if (preg_match($regex, $val))  {
    329                 $this->addError($form_name, $msg);
    330                 return false;
    331             } else {
    332                 return true;
    333             }
     305    function checkRegex($form_name, $regex, $valid_on_match, $msg='')
     306    {
     307        if (parent::checkRegex(getFormData($form_name), $regex, $valid_on_match)) {
     308            return true;
     309        } else {
     310            $this->addError($form_name, $msg);
     311            return false;
    334312        }
    335313    }
     
    347325    function stringLength($form_name, $min, $max, $msg='')
    348326    {
    349         $val = getFormData($form_name);
    350 
    351         if (strlen(trim($val)) < $min || strlen($val) > $max) {
    352             $this->addError($form_name, $msg);
    353             return false;
    354         } else {
    355             return true;
     327        if (parent::stringLength(getFormData($form_name), $min, $max)) {
     328            return true;
     329        } else {
     330            $this->addError($form_name, $msg);
     331            return false;
    356332        }
    357333    }
     
    369345    function numericRange($form_name, $min, $max, $msg='')
    370346    {
    371         $val = getFormData($form_name);
    372         if ($val != '' && is_numeric($val)) {
    373             if ($val < $min || $val > $max) {
    374                 $this->addError($form_name, $msg);
    375                 return false;
    376             }
    377             return true;
    378         } else {
    379             // Not a number!
     347        if (parent::numericRange(getFormData($form_name), $min, $max)) {
     348            return true;
     349        } else {
     350            $this->addError($form_name, $msg);
    380351            return false;
    381352        }
     
    399370    {
    400371        $app =& App::getInstance();
    401    
     372
    402373        $email = getFormData($form_name);
     374
    403375        if ('' == trim($email)) {
    404             return false;
    405         }
    406 
    407         require_once 'codebase/lib/Email.inc.php';
    408         $e = new Email();
    409 
    410         // Test email address format.
    411         if (!preg_match($e->getParam('regex'), $email, $e_parts)) {
    412             $this->addError($form_name, sprintf(_("%s is not a valid email address."), oTxt($email)));
     376            // No email address provided, and that's okay
     377            return true;
     378        }
     379
     380        // Validator::validateEmail() returns a value that relates to the VALIDATE_EMAIL_* constants (defined in Validator.inc.php).
     381        switch (parent::validateEmail($email)) {
     382        case VALIDATE_EMAIL_REGEX_FAIL:
     383            // Failed regex match.
     384            $this->addError($form_name, sprintf(_("<em>%s</em> is not a valid email address."), oTxt($email)));
    413385            $app->logMsg(sprintf('The email address %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
    414386            return false;
    415         }
    416 
    417         // We have a match! Here are the captured subpatterns, on which further tests are run.
    418         $local = $e_parts[2];
    419         // If domain is an IP [XXX.XXX.XXX.XXX] strip off the brackets.
    420         $domain = $e_parts[3]{0} == '[' ? substr($e_parts[3], 1, -1) : $e_parts[3];
    421 
    422         // Test length.
    423         if (strlen($local) > 64 || strlen($domain) > 191) {
    424             $this->addError($form_name, sprintf(_("<strong>Email address</strong> must contain less than 256 characters."), oTxt($email)));
     387            break;
     388        case VALIDATE_EMAIL_LENGTH_FAIL :
     389            // Failed length requirements.
     390            $this->addError($form_name, sprintf(_("<em>Email address</em> must contain less than 256 characters."), oTxt($email)));
    425391            $app->logMsg(sprintf('The email address %s must contain less than 256 characters.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
    426392            return false;
    427         }
    428 
    429         // Check domain exists: It's a domain if ip2long fails; Checkdnsrr ensures a MX record exists; Gethostbyname() ensures the domain exists.
    430         // Compare ip2long twice for php4 backwards compat.
    431         if ((ip2long($domain) == '-1' || ip2long($domain) === false) && function_exists('checkdnsrr') && !checkdnsrr($domain . '.', 'MX') && gethostbyname($domain) == $domain) {
    432             $this->addError($form_name, sprintf(_("%s is not a valid email domain name"), oTxt($domain)));
     393            break;
     394        case VALIDATE_EMAIL_MX_FAIL :
     395            // Failed MX record test.
     396            $this->addError($form_name, sprintf(_("<em>%s</em> is not a valid email domain name"), oTxt($domain)));
    433397            $app->logMsg(sprintf('The email address %s contains an invalid email domain name (%s).', getFormData($form_name), $domain), LOG_INFO, __FILE__, __LINE__);
    434398            return false;
    435         }
    436 
    437         return true;
     399            break;
     400        case VALIDATE_EMAIL_SUCCESS :
     401        default :
     402            return true;
     403            break;
     404        }
    438405    }
    439406
     
    441408     * Check whether input is a valid phone number. Notice: it is now set
    442409     * to allow characters like - or () or + so people can type in a phone
    443      * number that looks like: +1 (530) 624-4410
     410     * number that looks like: +1 (530) 555-1212
    444411     *
    445412     * @param  string  $form_name the name of the incoming form variable
     
    451418        $phone = getFormData($form_name);
    452419
    453         return $this->checkRegex($form_name, '/^[0-9 +().-]*$/', true, sprintf(_("The phone number %s is not valid."), $phone))
    454         && $this->stringLength($form_name, 0, 25, sprintf(_("The phone number %s is too long"), $phone));
     420        return (
     421            $this->checkRegex($form_name, '/^[0-9 +().-]*$/', true, sprintf(_("The phone number <em>%s</em> is not valid."), $phone))
     422            && $this->stringLength($form_name, 0, 25, sprintf(_("The phone number <em>%s</em> is too long"), $phone))
     423        );
    455424    }
    456425
     
    465434    function validateStrDate($form_name, $msg='')
    466435    {
    467         $app =& App::getInstance();
    468    
    469         if (($timestamp = strtotime(getFormData($form_name, '0'))) === -1) {
     436        $app =& App::getInstance();
     437
     438        if (parent::validateStrDate(getFormData($form_name))) {
     439            return true;
     440        } else {
    470441            $this->addError($form_name, $msg);
    471442            $app->logMsg(sprintf('The string date %s is not valid.', getFormData($form_name)), LOG_DEBUG, __FILE__, __LINE__);
    472443            return false;
    473         } else {
    474             return true;
    475444        }
    476445    }
     
    481450     *
    482451     * @param  string  $form_name   The name of the incoming form variable.
    483      * @param  string  $cc_num      Card number to verify.
    484      * @param  string  $cc_type     Optional, card type to do specific checks.
     452     * @param  string  $cc_type     Optional, card type to do specific checks. One of the CC_TYPE_* constants.
    485453     *
    486454     * @return bool    true if no errors found, false otherwise
    487455     */
    488     function validateCCNumber($form_name, $cc_num=null, $cc_type=null)
    489     {
    490         if (!isset($cc_num)) {
    491             $cc_num = getFormData($form_name);
    492         }
    493 
    494         if ('' == $cc_num) {
    495             return false;
    496         }
    497 
    498         // Innocent until proven guilty
    499         $card_is_valid = true;
    500 
    501         // Get rid of any non-digits
    502         $cc_num = preg_replace('/[^\d]/', '', $cc_num);
    503 
    504         // Perform card-specific checks, if applicable
    505         switch (strtolower($cc_type)) {
    506             case 'visa' :
    507                 $card_is_valid = preg_match('/^4\d{15}$|^4\d{12}$/', $cc_num);
    508                 break;
    509             case 'mastercard' :
    510             case 'mc' :
    511                 $card_is_valid = preg_match('/^5[1-5]\d{14}$/', $cc_num);
    512                 break;
    513             case 'american_express' :
    514             case 'american_ex' :
    515             case 'americanexpress' :
    516             case 'americanex' :
    517             case 'am_ex' :
    518             case 'amex' :
    519             case 'ae' :
    520                 $card_is_valid = preg_match('/^3[47]\d{13}$/', $cc_num);
    521                 break;
    522             case 'discover' :
    523                 $card_is_valid = preg_match('/^6011\d{12}$/', $cc_num);
    524                 break;
    525             case 'diners_club' :
    526             case 'dinersclub' :
    527             case 'diners' :
    528             case 'diner' :
    529             case 'dc' :
    530                 $card_is_valid = preg_match('/^30[0-5]\d{11}$|^3[68]\d{12}$/', $cc_num);
    531                 break;
    532             case 'jcb' :
    533                 $card_is_valid = preg_match('/^3\d{15}$|^2131|1800\d{11}$/', $cc_num);
    534                 break;
    535         }
    536 
    537         // The Luhn formula works right to left, so reverse the number.
    538         $cc_num = strrev($cc_num);
    539 
    540         $luhn_total = 0;
    541 
    542         $num = strlen($cc_num);
    543         for ($i=0; $i<$num; $i++) {
    544             // Get each digit.
    545             $digit = substr($cc_num, $i, 1);
    546 
    547             //  If it's an odd digit, double it.
    548             if ($i / 2 != floor($i / 2)) {
    549                 $digit *= 2;
    550             }
    551 
    552             //  If the result is two digits, add them.
    553             if (strlen($digit) == 2) {
    554                 $digit = substr($digit, 0, 1) + substr($digit, 1, 1);
    555             }
    556 
    557             //  Add the current digit to the $luhn_total.
    558             $luhn_total += $digit;
    559         }
    560 
    561         // If it passed (or bypassed) the card-specific check and the Total is evenly divisible by 10, it's cool!
    562         if ($card_is_valid && $luhn_total % 10 == 0) {
    563             return true;
    564         } else {
    565             $this->addError($form_name, _("The <strong>credit card number</strong> you entered is not valid."));
     456    function validateCCNumber($form_name, $cc_type=null)
     457    {
     458        $cc_num = getFormData($form_name);
     459       
     460        if (parent::validateCCNumber($cc_num, $cc_type)) {
     461            return true;
     462        } else {
     463            $this->addError($form_name, sprintf(_("<em>%s</em> is not a valid credit card number."), $cc_num));
    566464            return false;
    567465        }
     
    576474     * @return bool   true if no errors found, false otherwise
    577475     */
    578     function validateFile($form_name, $msg='')
    579     {
    580         if (!isset($_FILES[$form_name]['tmp_name']) || '' == trim($_FILES[$form_name]['tmp_name'])) {
    581             $this->addError($form_name, $msg);
    582             return false;
    583         } else {
    584             return true;
     476    function fileUploaded($form_name, $msg='')
     477    {
     478        if (parent::fileUploaded($form_name)) {
     479            return true;
     480        } else {
     481            $this->addError($form_name, $msg);
     482            return false;
    585483        }
    586484    }
Note: See TracChangeset for help on using the changeset viewer.