if i understand correctly you want server side validation only if value is entered. I am exactly in the same scenario. I want to validate a URL only if the URL is provided. The best way i came across was to write my own custom validation class. You can write a generic custom validation class.
I followed this link https://symfony-docs-chs.readthedocs.org/en/2.0/cookbook/validation/custom_constraint.html except for few changes because of symfony's latest version.
Here is the implementation
Acme\BundleNameBundle\Validator\Constraints\cstmUrl
namespace Acme\BundleNameBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Url;
/**
* @Annotation
*/
class CstmUrl extends Url
{
public $message = 'The URL "%string%" is not valid';
}
Acme\BundleNameBundle\Validator\Constraints\cstmUrlValidator
namespace Acme\BundleNameBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\UrlValidator;
class CstmUrlValidator extends UrlValidator
{
public function validate($value, Constraint $constraint)
{
if(!$value || empty($value))
return true;
parent::validate($value, $constraint);
}
}
Validtion.yml
Acme\BundleNameBundle\Entity\Student:
Url:
- Acme\BundleNameBundle\Validator\Constraints\CstmUrl: ~
inside Controller just bind the constraint you normally would do
'constraints'=> new CstmUrl(array("message"=>"Invalid url provided"))
I am sure there can be other better ways of doing it, but for now i feel this does the job well.