jqueryvalidationlaravel-5jquery-validation-engineremote-validation

jQuery remote validation on create vs update


I have a Laravel 5.4 backend with validation rules all set up and working fine.

I also implemented the jQuery Validation plugin for client side validation for a better experience and used it successfully to test the remote validation.

So for example checking for a unique email address when adding an entity:

$("#customerForm").validate({
rules: {
    name: "required",
    email: {
        required: true,
        email: true,
        remote: {
            url: "/api/admin/customers/checkuniqueemail",
            type: "post",
            async: false,
            complete: function(data) {
                if (data.responseText == "true") { //i.e. email is unique
                    // show some feedback
                } 
            }
        }
    }
},
messages: {
    email: {
        remote: 'The email has already been taken.'
    }
}

});

This works perfectly.

Questions:

  1. The above example works great when I'm adding a new entity. I would also like to validate on Updates but in that case it should exclude the current entity when checking for a unique email. This would mean I need to pass the primary key of the current entity along as well. Is my approach correct, and would the "data" attribute be the recommended approach?

  2. Is there a way I can access the "action" attribute of the current form and send it along as a "data" variable.

The reason I ask is that the within the Laravel "Edit" form, the entity id is part of the action url (e.g. /customers/edit/1234) and not really within a hidden field. So if I can get ahold of the "action" and send its value along, I can extract the ID and check for uniqueness except for that entity. I'm using Route Model binding in case it's relevant

Thanks!


Solution

  • With jquery validate, you can use it much like the jquery ajax options. With that said, you can specify the data property. This property can take a static value or a function to return a dynamic value (the action attribute of the form you are submitting in your case)

    data: {'customer_id':function(){ return $('#customerForm').attr("action") } }