Skip to content

Commit 26acd30

Browse files
authored
Add section for preventing form submission in the form bindings guide (#3798)
* Add section for preventing form submission in the form bindings guide * Commit suggestions from maintainers
1 parent 066845e commit 26acd30

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

guides/client/form-bindings.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,3 +408,40 @@ document.getElementById("my-form").dispatchEvent(
408408
new Event("submit", {bubbles: true, cancelable: true})
409409
)
410410
```
411+
412+
## Preventing form submission with JavaScript
413+
414+
In some cases, you may want to conditionally prevent form submission based on client-side validation or other business logic before allowing a `phx-submit` to be processed by the server.
415+
416+
JavaScript can be used to prevent the default form submission behavior, for example with a [hook](js-interop.md#client-hooks-via-phx-hook):
417+
418+
```javascript
419+
/**
420+
* @type {import("phoenix_live_view").HooksOptions}
421+
*/
422+
let Hooks = {}
423+
Hooks.CustomFormSubmission = {
424+
mounted() {
425+
this.el.addEventListener("submit", (event) => {
426+
if (!this.shouldSubmit()) {
427+
// prevent the event from bubbling to the default LiveView handler
428+
event.stopPropagation()
429+
// prevent the default browser behavior (submitting the form over HTTP)
430+
event.preventDefault()
431+
}
432+
})
433+
},
434+
shouldSubmit() {
435+
// Check if we should submit the form
436+
...
437+
}
438+
}
439+
```
440+
441+
This hook can be set on your form as such:
442+
443+
```heex
444+
<form phx-hook="CustomFormSubmission">
445+
<input type="text" name="text" value={@text}>
446+
</form>
447+
```

0 commit comments

Comments
 (0)