Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

codeigniter form validation rules url

How can I validate form field which has URL as input value.

I tried with following rules. But it allows the field if the user input a string.

View File:

<?php $data = array(
                    'name'        => 'com_url',
                    'id'          => 'com_url',
                    'value'       => set_value('com_url'),
                    'placeholder' => $this->lang->line('register_com_url'),
                    'class'       => 'form-control',
                    'maxlength'  => 100

                  );
                  echo form_input($data);
            ?>

Config:

array(
    'field'   => 'com_url',
    'label'   => 'Com URL',
    'rules'   => 'trim|required|prep_url'
)

I user prep_url but it adds just http:// in the field but didn't validate the field for URL.

My Field should accept only the following formats:

http://www.sample.com

www.sample.com

http://sample.com

How can I do this?

like image 989
DonOfDen Avatar asked Feb 10 '15 04:02

DonOfDen


1 Answers

You can add this to your Form_validation.php file to check url syntax, or even check if the actual URL exists.

/**
 * Validate URL
 *
 * @access    public
 * @param    string
 * @return    string
 */
function valid_url($url)
{
    $pattern = "/^((ht|f)tp(s?)\:\/\/|~/|/)?([w]{2}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?/";
    if (!preg_match($pattern, $url))
    {
        return FALSE;
    }

    return TRUE;
}

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

/**
 * Real URL
 *
 * @access    public
 * @param    string
 * @return    string
 */
function real_url($url)
{
    return @fsockopen("$url", 80, $errno, $errstr, 30);
} 
like image 106
Bitwise Creative Avatar answered Sep 21 '22 10:09

Bitwise Creative