Reputation: 761
I'm working on the validation of one of my form in Symfony. My form as four field; the two first are for same information that can be any text or heaven empty. My third field is for the url of a web site and the fourth is for the url of my linkedin.
Right now, the only validation I have makes shure that my two url are url that start by either http or https, but since my fields are url fields, it already adds it at the start, so it's basically always correct what ever I write. Of curse, it works to if I doesn't put anything, but I want that to.
I was wandering if there were validation class that could help me make more validation, like checking if the addresse exist or if the linkedin is actually an url for linkedin?
Here is my code
Form:
<?php
namespace AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
Class ModifierInfosType extends AbstractType
{
public function buildForm(FormBuilderInterface $constructeur, array $options)
{
$constructeur
->add('travailFr', 'text', array('label'=>'Travail (Fr)'))
->add('travailEn', 'text', array('label'=>'Travail (En)'))
->add('lien', 'url', array('label'=>'Lien travail'))
->add('linkedin', 'url', array('label'=>'LinkedIn'))
->add('Modifier', 'submit');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AdminBundle\Entity\Infos',
));
}
public function getName()
{
return 'portfolio_modifier_info';
}
}
Validation field (PublicBundle\ressources\config\validation.yml):
PublicBundle\Entity\Infos:
properties:
lien:
- Url:
linkedin:
- Url:
Upvotes: 2
Views: 4352
Reputation: 761
I found a way to check that the url exist and work:
I did a custum validation:
<?php
namespace AdminBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
Class ContrainteUrlExistValidator extends ConstraintValidator
{
public function validate($url, Constraint $constraint)
{
//Vérifie si l'url peut être vide
if(empty($url)&&$constraint->peutEtreVide)
{
return;
}
//Pattern pour trouver les url qui commence par http:// ou https://
$pattern='/^(https?:\/\/)/';
//Valide l'url et s'assure le preg_match a trouvé un match
if(filter_var($url, FILTER_VALIDATE_URL)&&!empty(preg_match($pattern, $url, $matches)))
{
//Trouve l'host
$hostname=parse_url($url, PHP_URL_HOST);
//Tente de trouver l'adresse IP de l'host
if (gethostbyname($hostname) !== $hostname)
{
//Cherche les données de l'entête
$headers=get_headers($url);
//Tente de trouver une erreur 404
if(!strpos($headers[0], '404'))
{
return;
}
}
}
//Crée une erreur
$this->context->buildViolation($constraint->message)
->setParameter('%string%', $url)
->addViolation();
}
}
Upvotes: 2