Developed with love by KnpLabs Hire us for your project!
27

parsley-bundle

by jben87

Convert Symfony constraints into data-attributes for client-side validation with Parsley.

ParsleyBundle

Build Status
Scrutinizer Code Quality
Code Coverage

Convert Symfony constraints into data-attributes for client-side validation with Parsley.

Installation

Install the bundle with composer:

composer require j-ben87/parsley-bundle

Install Parsley library: http://parsleyjs.org/doc/index.html#installation

Configuration

The bundle exposes a basic configuration:

jben87_parsley:
    enabled: true           # enable/disable Parsley validation globally (can be enabled on FormType or Constraint level)
    trigger_event: 'blur'   # the JavaScript event for which the validation is to be triggered (relative to the selected input)

Usage

Form constraints

Create a FormType.

Any supported constraints you have defined on your form will automatically be turned into Parsley data-attributes.

Yes, it's that simple!

<?php

namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;

class CustomType extends AbstractType
{
    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('title', TextType::class, [
                'constraints' => [
                    new Assert\NotBlank(),
                    new Assert\Length(30),
                ],
            ])
            ->add('content', TextareaType::class, [
                'constraints' => [
                    new Assert\NotBlank(),
                ],
            ])
        ;
    }
}

Results in:

<!-- {{ form_widget(form.title) }} -->
<input type="text" id="title" name="title" required="required" data-parsley-trigger="blur" data-parsley-required="true" data-parsley-required-message="This value should not be blank." data-parsley-length="[30, 30]" data-parsley-length-message="This value should have exactly 30 characters.">

<!-- {{ form_widget(form.content }} -->
<textarea id="content" name="content" required="required" data-parsley-trigger="blur" data-parsley-required="true" data-parsley-required-message="This value should not be blank."></textarea>

data-class constraints

Create a FormType and configure its data-class option.

Any supported constraint you have defined on your class will automatically be turned into Parsley data-attributes.

Here again, it's incredibly simple!

<?php

namespace App\Model;

use Symfony\Component\Validator\Constraints as Assert;

class User
{
    /**
     * @var string
     *
     * @Assert\NotBlank
     * @Assert\Length(max=255)
     */
    private $username;

    /**
     * @var string
     *
     * @Assert\NotBlank
     * @Assert\Length(max=255)
     * @Assert\Email
     */
    private $email;
}

And

<?php

namespace App\Form\Type;

use App\Model\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('username')
            ->add('email')
        ;
    }

    /**
     * @inheritdoc
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

Results in:

{% {{ form_widget(form.username) }} %}
<input type="text" id="username" name="username" required="required" maxlength="255" data-parsley-trigger="blur" data-parsley-required="true" data-parsley-required-message="This value should not be blank." data-parsley-maxlength="255" data-parsley-maxlength-message="This value is too long. It should have 255 characters or less.">

{% {{ form_widget(form.email }} %}
<input type="email" id="email" name="email" required="required" maxlength="255" data-parsley-trigger="blur" data-parsley-required="true" data-parsley-required-message="This value should not be blank." data-parsley-maxlength="255" data-parsley-maxlength-message="This value is too long. It should have 255 characters or less." data-parsley-type="email" data-parsley-type-message="This value is not a valid email address.">

Notice: if you define the same constraint on both the FormType and the configured data-class, the FormType constraint will override the one configured on the data-class.

Internals

The ParsleyTypeExtension is where all the magic happens.

It gathers all Symfony constraints thanks to registered readers and turn them into Parsley constraints through factories.

It uses the special ChainFactory to automatically find the first factory that supports the given Symfony constraint.

Finally it normalizes the Parsley constraint into data-attributes and merge them with the FormView attributes.

Extending the bundle

You can easily add more constraints by:

  • creating a constraint that extends the abstract class JBen87\ParsleyBundle\Constraint\Constraint
  • creating a factory that implements the interface JBen87\ParsleyBundle\Constraint\Factory\FactoryInterface

Your factory will be automatically registered to be used by the ChainFactory service.

<?php

namespace App\Constraint\Constraints;

use JBen87\ParsleyBundle\Constraint\Constraint;

class Valid extends Constraint
{
    /**
     * @inheritdoc
     */
    protected function getAttribute(): string
    {
        return 'data-parsley-valid';
    }

    /**
     * @inheritdoc
     */
    protected function getValue(): string
    {
        return 'true';
    }
}
<?php

namespace App\Constraint\Factory;

use App\Constraint\Constraints as ParsleyAssert;
use JBen87\ParsleyBundle\Constraint\Constraint;
use JBen87\ParsleyBundle\Constraint\Factory\FactoryTrait;
use JBen87\ParsleyBundle\Constraint\Factory\TranslatableFactoryInterface;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
use Symfony\Component\Validator\Constraints as Assert;

class ValidFactory implements TranslatableFactoryInterface
{
    use FactoryTrait;

    /**
     * @inheritdoc
     */
    public function create(SymfonyConstraint $constraint): Constraint
    {
        /** @var Assert\Valid $constraint */

        return new ParsleyAssert\Valid([
            'message' => $this->trans($constraint->message),
        ]);
    }

    /**
     * @inheritdoc
     */
    public function supports(SymfonyConstraint $constraint): bool
    {
        return $constraint instanceof Assert\Valid;
    }
}

Supported constraints

The following Symfony constraints are currently supported:

  • Symfony\Component\Validator\Constraints\Date
  • Symfony\Component\Validator\Constraints\DateTime
  • Symfony\Component\Validator\Constraints\Email
  • Symfony\Component\Validator\Constraints\GreaterThan
  • Symfony\Component\Validator\Constraints\GreaterThanOrEqual
  • Symfony\Component\Validator\Constraints\Length
  • Symfony\Component\Validator\Constraints\LessThan
  • Symfony\Component\Validator\Constraints\LessThanOrEqual
  • Symfony\Component\Validator\Constraints\NotBlank
  • Symfony\Component\Validator\Constraints\Range
  • Symfony\Component\Validator\Constraints\Time
  • Symfony\Component\Validator\Constraints\Type
  • Symfony\Component\Validator\Constraints\Url

What's next

  • Support more constraints
  • Support group validation
The MIT License (MIT)

Copyright (c) 2015 Benoit Jouhaud

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
:
global: true
trigger_event: blur
date_time_pattern:

# Prototype
name: []
date_pattern:

# Prototype
name: []
time_pattern:

# Prototype
name: []
  • Update supported constraints in README
    By J-Ben87, 1 month ago
  • Enrich factory tests
    By J-Ben87, 1 month ago
  • Add missing extra parsley constraints
    By J-Ben87, 1 month ago
  • Add missing built-in parsley constraints
    By J-Ben87, 1 month ago
  • Update README
    By J-Ben87, 1 month ago
  • Rename EntityReader => DataClassReader
    By J-Ben87, 1 month ago
  • Fix type hinting issue
    By J-Ben87, 1 month ago
  • v2: symfony 4 support
    By J-Ben87, 1 month ago
  • Add LessThan constraint
    By J-Ben87, 1 year ago
  • Add missing tests for GreaterThan constraint
    By J-Ben87, 1 year ago
  • Merge pull request #10 from vkost/more_constraints
    By web-flow, 1 year ago
  • Add GreaterThan constraint (requires additional JS from ParsleyJS package to be included)
    By vkost, 1 year ago
  • Merge pull request #9 from J-Ben87/unsupported_constraints
    By web-flow, 1 year ago
  • Log unsupported constraints rather than throwing an exception (credits @djbfmeel)
    By J-Ben87, 1 year ago
  • Merge pull request #6 from BenoitLeveque/fix-compat-issue
    By web-flow, 1 year ago
  • fix test issue with symfony >=3.0
    By BenoitLeveque, 1 year ago
  • Fix invalid container parameters name
    By BenoitLeveque, 1 year ago
  • Fix symfony 3.0 issue with the form extension
    By BenoitLeveque, 1 year ago
  • Merge pull request #5 from BenoitLeveque/add-symfony-3-compat
    By web-flow, 1 year ago
  • Add symfony 3.0 compatibily
    By BenoitLeveque, 1 year ago
  • Merge pull request #4 from BenoitLeveque/add-php7-symfony-28
    By web-flow, 1 year ago
  • Allow usage with PHP 7.0
    By BenoitLeveque, 1 year ago
  • Add an option to configure the date_time patterns
    By J-Ben87, 2 years ago
  • Merge branch 'master' of github.com:J-Ben87/ParsleyBundle
    By J-Ben87, 2 years ago
  • Create Pattern constraint for Parsley and use it for DateTime, Date and Time Symfony constraints
    By J-Ben87, 2 years ago
  • Fix wrong condition when checking if parsley is enabled
    By J-Ben87, 2 years ago
  • Fix tests
    By J-Ben87, 2 years ago
  • Expose a config option to enable Parsley globally or on a form basis
    By J-Ben87, 2 years ago
  • Add missing dependency
    By J-Ben87, 2 years ago
  • Merge pull request #3 from J-Ben87/entity-visitor
    By J-Ben87, 2 years ago