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

Laravel Jsvalidation Laravel Package

proengsoft/laravel-jsvalidation

Generate client-side form validation automatically from your Laravel rules, messages, validators, and FormRequest classes—no custom JavaScript needed. Built on jQuery Validation, supports localization, and uses AJAX for rules like unique/exists/active_url and custom rules.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require proengsoft/laravel-jsvalidation
    npm install jquery-validation  # If not using the bundled version
    

    Publish assets (if needed):

    php artisan vendor:publish --provider="Proengsoft\Jsvalidation\JsvalidationServiceProvider"
    
  2. Basic Usage: Include jQuery, Bootstrap JS (optional), and the package JS:

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="{{ asset('vendor/jsvalidation/js/jsvalidation.js') }}"></script>
    
  3. First Form Validation: Use the JsValidator facade in your Blade view:

    {!! JsValidator::formRequest('App\Http\Requests\StoreUserRequest') !!}
    

    Ensure your StoreUserRequest extends FormRequest with validation rules.

First Use Case

Validate a simple form with Laravel's built-in rules (e.g., required|email|min:6):

// StoreUserRequest.php
public function rules()
{
    return [
        'email' => 'required|email',
        'password' => 'required|min:6',
    ];
}

The package auto-generates client-side validation for these rules without manual JS.


Implementation Patterns

Core Workflows

  1. FormRequest Integration:

    • Best Practice: Use JsValidator::formRequest() for complex forms with custom validation logic.
    • Example:
      {!! JsValidator::formRequest('App\Http\Requests\UpdateProfileRequest') !!}
      
    • AJAX Fallback: Rules like unique, exists, or custom rules trigger server-side validation via AJAX.
  2. Manual Rule Validation: For simple forms, validate individual fields:

    {!! JsValidator::make('email', 'required|email') !!}
    
  3. Dynamic Rules: Use JsValidator::make() with dynamic rules (e.g., from a controller):

    $rules = ['name' => 'required|max:255'];
    echo JsValidator::make($rules);
    

Integration Tips

  • Laravel Collective HTML: Works seamlessly with @error directives and Form::model().

    {!! Form::open() !!}
    {!! JsValidator::formRequest('App\Http\Requests\StorePostRequest') !!}
    <div class="form-group">
        {!! Form::label('title') !!}
        {!! Form::text('title', null, ['class' => 'form-control']) !!}
        @error('title')
            <span class="text-danger">{{ $message }}</span>
        @enderror
    </div>
    {!! Form::close() !!}
    
  • Vue/React Integration: Use the package’s JS output in SPAs by rendering the validation script dynamically:

    // Vue example
    mounted() {
        const validator = `@php echo JsValidator::formRequest('App\Http\Requests\StoreUserRequest') @endphp`;
        this.$el.insertAdjacentHTML('beforeend', validator);
    }
    
  • Custom Error Messages: Leverage Laravel’s Validator::extend() and Validator::replacer()—messages sync automatically to the client.

Advanced Patterns

  1. Conditional Validation: Use Laravel’s sometimes or unless rules in FormRequest; the package mirrors this logic client-side.

  2. AJAX-Only Rules: For rules requiring server-side checks (e.g., unique), the package auto-generates AJAX calls:

    // Auto-generated AJAX for unique:users,email
    $.ajax({
        url: '/jsvalidation/unique',
        data: { field: 'email', value: 'test@example.com' },
        success: function(response) {
            if (!response.valid) {
                // Show error
            }
        }
    });
    
  3. Localization: Translations sync from Laravel’s resources/lang to the client. No manual JS translation files needed.


Gotchas and Tips

Pitfalls

  1. Unsupported Rules:

    • present: Not implemented (client-side JS cannot detect "not present" like PHP).
    • dateFormat with timezones: Fails client-side; use server-side validation or simplify the format.
    • Custom Rules: Must extend JsValidatorRule or use AJAX. Example:
      // CustomRule.php
      use Proengsoft\Jsvalidation\JsValidatorRule;
      class CustomRule extends JsValidatorRule {
          public function getJsValidator() {
              return 'function(value, element, params) { return value === "secret"; }';
          }
      }
      
  2. jQuery Dependency:

    • The package requires jQuery. If using a modern SPA, include it via CDN or bundle it.
  3. Caching Issues:

    • Clear Laravel’s view cache (php artisan view:clear) if validation rules change but client-side JS doesn’t update.
  4. AJAX Race Conditions:

    • Rapid form submissions may trigger duplicate AJAX requests. Handle with:
      $.ajaxSetup({
          beforeSend: function(xhr) {
              xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
          }
      });
      

Debugging Tips

  1. Inspect Generated JS: View the rendered HTML source to debug validation rules:

    <script type="text/javascript">
        // Auto-generated JS here
        $("#my-form").validate({
            rules: { /* ... */ },
            messages: { /* ... */ }
        });
    </script>
    
  2. Console Errors: Check browser console for jQuery Validation Plugin errors (e.g., missing fields or invalid rules).

  3. AJAX Debugging:

    • Enable Laravel’s APP_DEBUG=true to see server-side validation responses.
    • Use Chrome DevTools Network tab to inspect AJAX calls to /jsvalidation/unique or /jsvalidation/exists.

Extension Points

  1. Custom Rule Support: Extend the package by creating a JsValidatorRule for unsupported rules:

    // app/Rules/CustomRule.php
    namespace App\Rules;
    use Proengsoft\Jsvalidation\JsValidatorRule;
    class CustomRule extends JsValidatorRule {
        public function getJsValidator() {
            return 'function(value) { return value.length > 10; }';
        }
    }
    

    Register in config/jsvalidation.php:

    'rules' => [
        'custom' => \App\Rules\CustomRule::class,
    ],
    
  2. Override Defaults: Customize the jQuery Validation Plugin settings in config/jsvalidation.php:

    'jquery_validation' => [
        'ignore' => ':hidden',
        'errorClass' => 'is-invalid',
        'successClass' => 'is-valid',
    ],
    
  3. Asset Management:

    • For Laravel Mix/Vite, copy the bundled JS to your assets and customize:
      // resources/js/jsvalidation.js
      import { default as JsValidation } from 'laravel-jsvalidation';
      JsValidation.init(); // Customize init logic
      
    • Ensure the compiled file is included in your Blade template.

Performance Tips

  1. Lazy Loading: Load the JS validation script only when needed (e.g., on form focus):

    <form id="my-form">
        <!-- ... -->
    </form>
    <script>
        document.getElementById('my-form').addEventListener('focusin', function() {
            const script = document.createElement('script');
            script.src = "{{ asset('vendor/jsvalidation/js/jsvalidation.js') }}";
            document.body.appendChild(script);
        });
    </script>
    
  2. Minimize AJAX Calls: Batch AJAX validations for rules like unique by debouncing input:

    $(document).on('input', 'input[name="email"]', _.debounce(function() {
        JsValidation.validateField('email');
    }, 500));
    
  3. Disable for Non-Critical Forms: Skip validation for forms with minimal risk (e.g., guest newsletters):

    {!! JsValidator::formRequest('App\Http\Requests\NewsletterRequest', ['disable' => true]) !!}
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata