I’m using a callback to validate URLs submitted by a text input. I need to insert NULL in the database if the text input is empty (meaning the user erased his/her URL entry). I’m trying the code below but it just inserts an empty string in the database.
$this->form_validation->set_rules('image_url', 'Image URL', 'trim|xss_clean|prep_url|callback__validate_url');
The callback:
function _validate_url($str)
{
if (isset($str))
{
$pattern = "/^(http|https):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if (!preg_match($pattern, $str))
{
$this->form_validation->set_message('_validate_url', 'URL is not valid');
return FALSE;
}
else
{
if (!isset($str)) //if input empty
{
return NULL; //return NULL to input?
}
return TRUE;
}
}
return TRUE;
}
How can I return a value to the input via a callback?
Update:
The code above is wrong and I was not able to return NULL in the input (I’m guessing because its returns a string) so I did it outside the callback
$image_url = $this->input->post('image_url');
if (empty($image_url))
{
$image_url = NULL;
}
$data = array (
'content' => $this->input->post('content'),
'image_url' => $entry_image_url
);
//add to database
Look at this piece of code, it’s got an impossible condition:
Replace that condition with an appropriate way to check if the input is empty, perhaps check if
trim($str) === ''or evenempty($str).