HTML form validation and phx-change

Say I got an input like this

<.form for={@the_form} phx-change="form-changed">
  <.input
    type="number"
    field={@the_form[:number]}
    max="10"
  />

Now if the input is :invalid (eg a number > 10) I still get form-changed events.
Is there any way to prevent that?
So that I only get values that HTML deems valid…?

1 Like

AFAIK there is no “pre-fire hook” for the change event. It’s firing on every keystroke and, beyond debounce and throttle, I’m not aware of it having any other options.

One thing you could create a client-side hook to attach to particular fields to check their “validity state” before sending their values to the server. But if you have phx-change on the form it’s still going to send everything else as well, but you could still add it to all other inputs that you don’t want this behaviour on instead of the form itself.

EDIT: You could also add the hook to the form itself and dynamically attach listeners to all of its inputs. It gets a little hairier with edge cases, though.

1 Like

OK, I think I’ll just forward HTMLElement: change event - Web APIs | MDN as it is good enough for me. For anyone trying sth similar be aware, that:

the change event fires …

  • When the element loses focus after its value was changed: for elements where the user’s interaction is typing rather than selection, such as a <textarea> or the text, search, url, tel, email, or password types of the <input> element.
1 Like