Skip to content
Danqing NI edited this page Feb 11, 2014 · 18 revisions

Category:Library::Validation | Category:Library::Community

Introduction

Instead of using callbacks to add rules you can add rules by extending the validation library.

The error messages must be added to the validation language file.

All additions are welcome

Source

<?php
class MY_Validation extends CI_Validation
{
    var $_display_fieldname = array();
    
    function MY_Validation()
    {
        parent::CI_Validation();
    }
    /**
    * numeric rules
    *
    */
    function greater_than($str,$min)
    {
        if(!is_numeric($str)){ return false; }
        return $str > $min;
    }
    
    function less_than($str,$max)
    {
        if(!is_numeric($str)){ return false; }
        return $str < $max;
    }
    /*
    *  checkbox rules
    *
    * use with required rule
    */
    function equal_to($str,$eq)
    {
        if(!is_numeric($str)){ return false; }
        return $str == $eq; 
    }
    
    function max_count($str,$max)
    {
        return (count($str) <= $max);
    }
    
    function min_count($str,$min)
    {
        return count($str) >= $min;
    }
    /**
    *  email rules
    *
    */
    function domain_email($str,$params)
    {
        $parts = explode("@", $str);
        $domain = $parts[1];
        $allowed_array = explode(',',$params);
        return in_array($domain, $allowed_array);
    }
    /**
    *   general rules
    *
    */
    function exact_count($str,$eq)
    {
       if(is_string($str))
       { 
           return (strlen($str) == $eq)?true:false;
       }
       else
       {
          return count($str) == $eq;
       }
    }
    /*
    * validate date from 3 selects
    *
    * example : $rule['year'] = 'valid_selectsdate[month,day]';
    *
    */
    function valid_selectsdate($str,$params)
    {
       $explode = explode(',',$params);
       $month = $this->CI->input->post($explode[0]);
       $day = $this->CI->input->post($explode[1]);
       if(!$day) // year and month don't need to be validated
       {
          return true;
       }
       if(checkdate($month,$day,$str))
       {
           return true;
       }
       return false;
    }
    /*
    * validate date from text input
    *
    *
    * example : $rule['date'] = 'valid_textdate[-,2,1,0]';
    */
    function valid_textdate($str,$params= '')
    {
       if($params == '')
       {
           // default setting
           $divider = '-';
           $yearpart = 0;
           $monthpart = 1;
           $daypart = 2;
       }
       else
       {
           $explode = explode(',',$params);
           $divider = $explode[0];
           $yearpart = $explode[1];
           $monthpart = $explode[2];
           $daypart = $explode[3];
       }
       $explode2 = explode($divider,$str);
       if(count($explode2) != 3)
       {
               return false;
       }
       $year = $explode2[$yearpart];
       $month = $explode2[$monthpart];
       $day = $explode2[$daypart];
       if(checkdate($month,$day,$year))
       {
           return true;
       }
       return false;
    }
    
    /*
    *  set fields alternative
    *
    */
    function set_fields($data = '', $field = '', $separator = '_') {    
        if ($data == '') {
            if (count($this->_fields) == 0 && count($this->_rules) == 0) {
                return FALSE;
            }
        } else {
            if ( ! is_array($data)) {
                $data = array($data => $field);
            }
            
            if (count($data) > 0) {
                $this->_fields = $data;
            }
        }
        
        foreach($this->_rules as $key => $val) {                  
            $text = ucwords(str_replace($separator, ' ', $key));             
            $auto_fields[$key] = $text;     
        }
        
        $this->_fields = array_merge($auto_fields, $this->_fields);
        
        foreach($this->_fields as $key => $val) {        
            $this->$key = ( ! isset($_POST[$key]) OR is_array($_POST[$key])) ? '' : $this->prep_for_form($_POST[$key]);
            
            $error = $key.'_error';
            if ( ! isset($this->$error)) {
                $this->$error = '';
            }
        }        
    }
    
    /**
     * Single Space
     *
     * - converts multiple spaces to one space
     * 
     * eg. "a      b" -> "a b"
     *
     * @access    public
     * @param    string
     * @return    void
     */
    function single_space($str)
    {
        $_POST[$this->_current_field] = preg_replace('/  +/', ' ', $str);
    }

    /**
     * Alpha-numeric with underscores, dashes and spaces
     *
     * @access    public
     * @param    string
     * @return    bool
     */    
    function alpha_dash_space($str)
    {
        return ( ! preg_match("/^([-a-z0-9_- ])+$/i", $str)) ? FALSE : TRUE;
    }

}

Here's an addition, only returns true if the domain for an e-mail actually has MX or A records

/**
 * Checks if the given domain has e-mailadresses by checking MX an A records
 * on the fly.
 *
 * It takes a little longer but will return false for input with valid
 * syntax but a non-existing domain.
 *
 * @param String $str
 * @return Boolean
 */
function dns_email($str){

    // First, check syntax using CI valid_email function
    if (parent::valid_email($str)) { // email syntax is OK

        // This will split the email into its front
        // and back (the domain) portions
        list($name, $domain) = split('@',$str);

        // Check if domain has MX or A records (btw, this does NOT tell us if the
        // individual email address existst!)
        //return (!checkdnsrr($domain,'MX')) ? FALSE : TRUE;
        return (!(checkdnsrr($domain,"MX") || checkdnsrr($domain, "A"))) ? FALSE : TRUE;

    }
    else { // syntax is not OK
        return false;
    }

}

Here's an addition again. :)

/**
 * Array Rules, apply rauls to array values
 *
 * array_rules[integer], array_rules[max_length{255}]
 *
 * @access    public
 * @param    mixed
 * @param    string. this class methods or php functions,
 * @return    bool
 */
function array_rules($mixed, $rule='') {
    $mixed = is_array($mixed) ? $mixed : array($mixed);

    if ($rule == '') {
        return TRUE;
    }

    $result = TRUE;

    $param = FALSE;
    if (preg_match("/(.*?)\{(.*?)\}/", $rule, $match)) {
        $rule    = $match[1];
        $param    = $match[2];
    }

    foreach ($mixed as $field) {
        if ( ! method_exists($this, $rule)) {
            if (function_exists($rule)) {
                if (! $rule($field, $param)) {
                    $result = FALSE;
                    break;
                }
            }
            continue;
        }
        if (! $this->$rule($field, $param)) {
            $result = FALSE;
            break;
        }
    }
    return $result;
}

// --------------------------------------------------------------------

/**
 * Color Hex
 *
 * #ffffff
 *
 * @access    public
 * @param    string
 * @return    bool
 */
function color_hex($hex) {
    return (bool)preg_match("/#[a-fA-F0-9]{6}/", $hex);
}

// --------------------------------------------------------------------

/**
 * Color RGB
 *
 * RGB(255, 255, 255)
 *
 * @access    public
 * @param    string
 * @return    bool
 */
function color_rgb($rgb) {
    return (bool)preg_match("/rgb\([0-255]{1,3},\s?[0-255]{1,3},\s?[0-255]{1,3}\)/i", $rgb);
}

// --------------------------------------------------------------------

/**
 * ENUM
 *
 * enum[asc, desc]
 *
 * @access    public
 * @param    string, splict by comma
 * @return    bool
 */
 function enum($str, $val='') {
    if (empty($val))
        return FALSE;

    $arr = explode(',', $val);
    $array = array();
    foreach($arr as $value) {
        $array[] = trim($value);
    }
    unset($arr);
    return (in_array(trim($str), $array)) ? TRUE : FALSE;
 }

 /**
 * ENUMi Not case-sensitive
 *
 * enum[ASC, desc]
 *
 * @access    public
 * @param    string, splict by comma
 * @return    bool
 */
 function enumi($str, $val='') {
    if (empty($val))
        return FALSE;

    $arr = explode(',', $val);
    $array = array();
    foreach($arr as $value) {
        $array[] = strtolower(trim($value));
    }
    unset($arr);
    return (in_array(strtolower(trim($str)), $array)) ? TRUE : FALSE;
 }

// --------------------------------------------------------------------

/**
 * date_range
 *
 * enum[asc, desc]
 *
 * @access    public
 * @param    string, date range format is like as 20010101 - 20011231, date('Ymd');
 * @return    bool
 */
function date_range( $date_range ) {
    if ( preg_match( "/^\d{8}\s*-\s*\d{8}$/", $date_range ) ) {
        $dateArray = explode( '-', $date_range );
        return ( $this->_check_series_date( trim( $dateArray[0] ) ) && $this->_check_series_date( trim( $dateArray[1] ) ) );
    }
    return FALSE;
}

// --------------------------------------------------------------------

/**
 * _check_series_date
 *
 * @usage    enum[asc, desc]
 *
 * @access    private
 * @param    number
 * @return    bool
 */
private function _check_series_date( $series_date ) { // series date is like as 20080101, date('Ymd');
    return checkdate( intval( substr( $series_date, 4, 2 ) ), intval( substr( $series_date, 6, 2 ) ), intval( substr( $series_date, 0, 4 ) ) );
}
Clone this wiki locally