cferdinandi / validate

A lightweight form validation script.
MIT License
230 stars 39 forks source link

Event listeners registered by rails-ujs override/hijack the one added by validate.init() #33

Closed murdoch closed 7 years ago

murdoch commented 7 years ago

I'm using Rails 5 and rails-ujs and had to do a few things to get this library running smoothly:

rails-ujs (a javascript driver added by rails) attaches its own submit event listeners to the document. When a form with data-remote=true is submitted, the rails-ujs event listener kicks in and submits the form via ajax. This prevents the submit listener added by validate.init() from 'running'.

To fix this I had to two things:

1 - Use capturing. I had to change from the following:

document.addEventListener('submit', submitHandler, false);

to this:

document.addEventListener('submit', submitHandler, true);

2 - Stop propagation on failed validation:

// Prevent form from submitting if there are errors or submission is disabled
if (hasErrors || settings.disableSubmit) {
  event.preventDefault();
  event.stopPropagation();
}

Now everything works fine.

It's worth pointing out, that the blur handler and click handler are not affected by rails-ujs at all, they work as expected, it's just the submit handler that fails to do run when a form is submitetd via XHR.

cferdinandi commented 7 years ago

Thanks for posting this for anyone else who might run into this same issue. Closing it out, since this is a quirk of Rails UI taking over for default browser behavior, but great to have for archival purposes!