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

Jquery Validation Bundle Laravel Package

boekkooi/jquery-validation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require boekkooi/jquery-validation-bundle
    

    Enable the bundle in config/bundles.php:

    Boekkooi\JqueryValidationBundle\BoekkooiJqueryValidationBundle::class => ['all' => true],
    
  2. Basic Usage: Add the validation script to your base template (e.g., base.html.twig):

    {{ jquery_validation_bundle_js() }}
    
  3. First Use Case: Validate a form in a Twig template:

    {{ form_start(form) }}
        {{ form_widget(form) }}
        <button type="submit" class="validate">Submit</button>
    {{ form_end(form) }}
    

    Ensure the form has a validate class or use data-validate="true" on the submit button.


Key Configuration

  • Default Rules: Configure global validation rules in config/packages/boekkooi_jquery_validation.yaml:
    boekkooi_jquery_validation:
        default_rules: { email: { required: true, email: true } }
    

Implementation Patterns

Common Workflows

1. Form-Specific Validation

Override default rules per form in Twig:

{{ form_start(form, { 'attr': { 'data-validation-rules': '{"username": {"required": true, "minlength": 5}}' } }) }}

2. Dynamic Rules via Controller

Pass rules dynamically from a controller:

return $this->render('form.html.twig', [
    'form' => $form->createView(),
    'validation_rules' => json_encode(['password' => ['required' => true, 'minlength' => 8]]),
]);

Use in Twig:

{{ form_start(form, { 'attr': { 'data-validation-rules': validation_rules } }) }}

3. Custom Error Messages

Define custom messages in Twig:

{{ form_start(form, {
    'attr': {
        'data-validation-messages': '{
            "username": {"required": "Please enter your username"},
            "email": {"email": "Invalid email format"}
        }'
    }
}) }}

4. Integration with Symfony Forms

Use Symfony form errors to pre-populate validation errors:

{% for error in form.errors %}
    <div class="error">{{ error.message }}</div>
{% endfor %}

Integration Tips

Asset Management

  • Ensure jQuery and jQuery Validation plugin are loaded before the bundle’s JS:
    {{ encore_entry_link_tags('app') }} {# Webpack Encore #}
    {{ jquery_validation_bundle_js() }}
    

Laravel-Specific

  • For Laravel (Symfony-based), use public_path() in Twig to reference assets if needed:
    <script src="{{ asset('bundles/boekkoojqueryvalidation/js/jquery.validation.js') }}"></script>
    

Event Listeners

  • Extend validation logic via Twig events (e.g., modify rules dynamically):
    // In a service or controller
    $twig->addExtension(new \Your\Custom\ValidationExtension());
    

Gotchas and Tips

Pitfalls

  1. Outdated Dependencies:

    • The bundle was last updated in 2016 and may not work with modern Symfony/Laravel versions (5.4+).
    • Workaround: Fork the repo and update dependencies (e.g., symfony/form, twig) manually.
  2. Asset Path Conflicts:

    • If using Webpack Encore or Laravel Mix, the bundle’s default asset paths may clash.
    • Fix: Override asset paths in config/packages/boekkooi_jquery_validation.yaml:
      boekkooi_jquery_validation:
          js_path: '/build/bundle.js'  # Custom path
      
  3. Twig Template Caching:

    • Dynamic data-validation-rules may not update if Twig cache is aggressive.
    • Tip: Use {{ form_start(form, { 'attr': { 'data-validation-rules': validation_rules|raw } }) }} to bypass escaping issues.
  4. jQuery Version Mismatch:

    • The bundle assumes jQuery 1.x/2.x. For jQuery 3+, ensure compatibility by:
      // Add this to your custom JS
      $.validator.setDefaults({ ignore: '' }); // Fix for jQuery 3+
      

Debugging Tips

  1. Console Errors:

    • Check browser console for Uncaught ReferenceError or 404 on JS/CSS files.
    • Solution: Verify asset paths and ensure files are built (e.g., npm run dev).
  2. Validation Not Triggering:

    • Ensure the submit button has class="validate" or data-validate="true".
    • Debug: Add console.log("Validation initialized"); to the bundle’s JS file.
  3. Rules Not Applying:

    • Validate JSON syntax in data-validation-rules:
      console.log(JSON.parse('{"field": {"rule": true}}')); // Test in browser console
      

Extension Points

  1. Custom Validation Methods:

    • Extend jQuery Validation’s methods object in a custom JS file:
      $.validator.addMethod("custom_rule", function(value, element) {
          return value.length > 10; // Example
      }, "Value must be longer than 10 characters");
      
    • Reference it in Twig:
      data-validation-rules='{"field": {"custom_rule": true}}'
      
  2. Override Bundle Templates:

    • Copy Resources/views/Form/validation.html.twig to your theme and modify.
  3. Symfony Event Subscribers:

    • Listen to kernel.request to dynamically inject rules:
      public function onKernelRequest(GetResponseEvent $event) {
          $request = $event->getRequest();
          if ($request->attributes->get('_route') === 'custom_route') {
              $request->attributes->set('validation_rules', ['field' => ['required' => true]]);
          }
      }
      
    • Access in Twig via app.request.attributes.validation_rules.

Performance Considerations

  • Lazy-Loading: Load the bundle’s JS only on pages with forms using Twig’s {% block %}:
    {% block validation_js %}
        {{ jquery_validation_bundle_js() }}
    {% endblock %}
    
  • Minification: Bundle the JS with Webpack Encore to reduce HTTP requests.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui