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?
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);
} 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With