How can i validate a url field in zend framework. I tried the following code.
$website = $this->createElementText('website', 'Website');
$website->setOptions(
array(
'filters' => array(
'StringTrim',
'StripTags',
),
'validators' => array(
'NotEmpty',
array(
'Callback',
true,
array(
'callback' => function($value) {
// if (!strpos($value, 'http')) $value = 'http://' . $value;
return Zend_Uri::check($value);
}
),
'messages' => array(
Zend_Validate_Callback::INVALID_VALUE => 'Please enter a valid URL',
),
),
),
)
)->setErrorMessages(array('Please enter a valid URL. For e.g, http://test.com or http://www.test.com'));
$form->addElements(array($website));
But this is not accurate. For example it is not giving errors for urls like htt://www.google
How can i improve my validation.Is there any other method?
Personally, I use a custum validator which has the advantage that it can be reused easily without having to recode it for each field.
There are many examples in the web like here or here or here (in french) ...
After coding Your_Validate_Uri
class you can do this:
$website->addValidator(new Your_Validate_Uri());
I hope it will help you. :)
I use something like this and my work as it should:
'validators' => array(
array(
'validator' => 'Callback',
'options' => array(
'callback' => function ($value) {
if (!filter_var($value, FILTER_VALIDATE_URL) === false) {
return true;
} else {
return false;
}
},
'messages' => 'This is not a valid url address'
),
'breakChainOnFailure' => true
),
),
Good Luck ;)