Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Form Js Validation Bundle Laravel Package

acseo/form-js-validation-bundle

Symfony bundle that adds client-side JavaScript validation to Symfony forms. Choose between formvalidation.io or jqueryvalidation.org, enable the service in parameters.yml, call addJsValidation() in controllers, and initialize validation in your Twig template.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require acseo/form-js-validation-bundle
    

    Register the bundle in AppKernel.php:

    new ACSEO\Bundle\FormJsValidationBundle\ACSEOFormJsValidationBundle(),
    
  2. Configure Validation Plugin: Choose either validation.io or jqueryvalidation.org in config/parameters.yml:

    parameters:
        acseo_form_js_validation.service: acseo_form_js_validation_io  # or acseo_form_jquery_form_validator
    
  3. First Use Case: In a controller, add JS validation to a form:

    $form = $this->createForm(AwesomeEntityType::class, $entity);
    $form = $this->get('acseo_form_js_validation.service')->addJsValidation($form);
    return $this->render('template.html.twig', ['form' => $form->createView()]);
    
  4. Template Setup:

    • For validation.io, include its JS/CSS in your base template:
      <link rel="stylesheet" href="https://formvalidation.io/css/formValidation.min.css">
      <script src="https://formvalidation.io/js/formValidation.min.js"></script>
      
    • For jqueryvalidation.org, include jQuery and the validator:
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
      

Implementation Patterns

Core Workflow

  1. Form Integration:

    • Use addJsValidation() on any Symfony form instance (e.g., FormType, EntityType).
    • Works seamlessly with Symfony’s form theme system (e.g., form_div_layout.html.twig).
  2. Dynamic Validation Rules:

    • The bundle auto-maps Symfony form constraints (e.g., @Assert\NotBlank, @Assert\Email) to JS validation rules.
    • Example: A NotBlank constraint becomes data-fv-notempty="true" in HTML.
  3. Customization:

    • Override default JS rules via Twig:
      {{ form_widget(form.field, {'attr': {'data-fv-remote': 'true', 'data-fv-remote-url': path('check_field')}}) }}
      
    • Extend the bundle’s validator service to add custom logic (see "Gotchas").
  4. Event-Driven Extensions:

    • Listen to form.pre_set_data or form.post_bind to dynamically modify validation rules:
      $form->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
          $form = $event->getForm();
          $form->add('custom_field', TextType::class, [
              'constraints' => [new CustomConstraint()],
          ]);
      });
      
  5. Asset Management:

    • Use Symfony’s asset system to load JS/CSS:
      {% block javascripts %}
          {{ parent() }}
          {{ encore_entry_script_tags('app') }}  {# If using Webpack Encore #}
      {% endblock %}
      

Gotchas and Tips

Common Pitfalls

  1. Outdated Dependencies:

    • The bundle was last updated in 2017. Test thoroughly with modern Symfony (5.4+/6.x) and PHP 8.x.
    • Workaround: Fork the repo and update dependencies (e.g., Symfony Form/Validator components).
  2. Missing JS/CSS:

    • Forgetting to include validation.io or jQuery/jQuery Validate JS/CSS will break validation.
    • Fix: Verify the base template includes the required assets (see "Getting Started").
  3. Constraint Mismatches:

    • Complex constraints (e.g., @Assert\Callback) may not map cleanly to JS.
    • Tip: Use data-fv-custom attributes for custom rules:
      {{ form_widget(form.field, {'attr': {'data-fv-custom': 'function(value) { return value > 10; }'}}) }}
      
  4. Service Configuration:

    • Incorrect parameters.yml setting (e.g., typo in service name) will throw ServiceNotFoundException.
    • Debug: Check bin/console debug:container acseo_form_js_validation.service to verify the service is registered.
  5. Form Theme Conflicts:

    • Custom form themes may override the bundle’s HTML attributes.
    • Solution: Extend the default theme or use form_row with explicit attributes:
      {{ form_row(form.field, {'attr': {'data-fv-required': 'true'}}) }}
      

Debugging Tips

  1. Inspect Generated HTML:

    • Use browser dev tools to verify attributes like data-fv-* are rendered correctly.
    • Example: A NotBlank field should have data-fv-notempty="true".
  2. Console Logs:

    • For validation.io, check browser console for errors like:
      FormValidation: No form found with id "form-id"
      
    • Fix: Ensure the form has an id (Symfony adds this by default).
  3. Remote Validation:

    • If using data-fv-remote, ensure the endpoint returns:
      {"valid": true/false}
      
    • Tip: Test the endpoint separately (e.g., with Postman).

Extension Points

  1. Custom Validators:

    • Extend the service to support new constraints:
      // src/Service/CustomValidator.php
      class CustomValidator extends AbstractValidator
      {
          protected function getJsRules(array $constraints): array
          {
              $rules = parent::getJsRules($constraints);
              $rules['custom_field'] = ['data-fv-custom': '...'];
              return $rules;
          }
      }
      
    • Register the service in services.yaml:
      services:
          acseo_form_js_validation.service:
              class: App\Service\CustomValidator
              tags: ['acseo.form_js_validation.validator']
      
  2. Dynamic Rule Injection:

    • Use Twig’s form_widget with custom attributes:
      {{ form_widget(form.field, {
          'attr': {
              'data-fv-remote': 'true',
              'data-fv-remote-url': path('validate_field', {'_locale': app.request.locale}),
              'data-fv-remote-message': 'Field is already taken'
          }
      }) }}
      
  3. Localization:

    • Override default error messages in translations/messages.en.yml:
      validation:
          not_blank: "This field cannot be empty."
      
    • Pass the locale to the JS validator:
      <script>
          FormValidation.formValidation(document.getElementById('form-id'), {
              fields: {
                  field_name: {
                      validators: {
                          notEmpty: { message: '{{ 'validation.not_blank'|trans }}' }
                      }
                  }
              }
          });
      </script>
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai