Rails_ujs and stopping a form submission


#1

I’m trying to stop a form submission if a specific field is filled in. It appears that returning false doesn’t cancel the ajax event when built using stimulus.

import { Controller } from 'stimulus'

export default class extends Controller {
  static targets = [ 'url' ]

  before() {
    if (this.urlTarget.value != '') {
      console.log('gotcha')
      return false
    }
  }
}
= form_with url: 'someurl', data: { controller: 'contact', action: 'ajax:before->contact#before' } do |f|
  .url= f.text_field :url, data: { target: 'contact.url' }
  .submit= f.button 'Send Email'

#2

So it turns out a return false doesn’t work but event.preventDefault() does.


#3

I think you need to use the event Ajax:beforeSend.

Your question is similar to this topic where you will have a more detailed answer


#4

Ajax:beforeSend didn’t work either when returning false. Thanks for the link to the issue.


#5

It looks like you can pass the event as an argument to the before() function. Once you have that you can call preventDefault()

Basing this on the handbook section here:
https://stimulusjs.org/handbook/building-something-real#actions-and-targets-can-go-on-any-kind-of-element