Rails_ujs and stopping a form submission

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'

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

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

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

1 Like

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