Welcome Guest, Not a member yet? Register   Sign In
Form validation url-check
#6

[eluser]Khoa[/eluser]
We can extend the Form_Validation class to integrate this validation into the core class so that we can just use it as any other validation rules.

By combining the reg exp from manilodisan and with the help of how to extend a form validation at this blog http://www.scottnelle.com/41/extending-c...n-library/, I created this extension to the Form_Validation to include the valid_url() function.

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* MY_Form_Validation Class
*
* Extends Validation library
*
* Adds one validation rule, valid_url to check if a field contains valid url
*/

class MY_Form_Validation extends CI_Form_validation {

    function MY_Form_Validation()
    {
        parent::CI_Form_validation();
    }

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

    /**
     * valid_url
     *
     * @access    public
     * @param    field
     * @return    bool
     */
    function valid_url($field)
    {
        $CI =& get_instance();
        
        $CI->form_validation->set_message('valid_url', 'The %s field must contain a valid url.');

        return ( ! preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $field)) ? FALSE : TRUE;
    }
}
?>

For those who are new to extending the core libraries (including myself), you need to save this file at: system\application\libraries\MY_Form_Validation.php (make sure you name the file name and its case correctly). Then you can just use it as normal, CI will cleverly pick it up.

Code:
$rules = array(
    array
    (
        'field' => 'websiteURL',
        'label'    => 'Website',
        'rules'    => 'required|max_length[255]|valid_url'
    ),
);

$this->load->library('form_validation');
$this->form_validation->set_rules($rules);

if ($this->form_validation->run())
{
    //...
}
else
{
    //...
}

Hope this helps.

Khoa


Messages In This Thread
Form validation url-check - by El Forum - 11-25-2008, 05:13 PM
Form validation url-check - by El Forum - 11-26-2008, 03:38 PM
Form validation url-check - by El Forum - 11-26-2008, 05:43 PM
Form validation url-check - by El Forum - 11-27-2008, 08:07 PM
Form validation url-check - by El Forum - 06-05-2009, 07:40 AM
Form validation url-check - by El Forum - 06-06-2009, 08:11 AM
Form validation url-check - by El Forum - 06-06-2009, 08:44 AM
Form validation url-check - by El Forum - 06-06-2009, 09:46 PM
Form validation url-check - by El Forum - 06-06-2009, 09:59 PM
Form validation url-check - by El Forum - 06-08-2009, 03:04 AM



Theme © iAndrew 2016 - Forum software by © MyBB