oruga-ui / oruga

🐛 Oruga is a lightweight library of UI components without any CSS framework dependency
https://oruga-ui.com
MIT License
1.12k stars 171 forks source link

FormElementMixin should listen for the `invalid` event #407

Closed blm768 closed 1 year ago

blm768 commented 2 years ago

Overview of the problem

Oruga version: 0.5.5 VueJS version: 3.2.33 (probably affects 2.x as well) OS/Browser: (all)

Description

FormElementMixin checks for HTML5 constraint validation errors on blur and updates the parent field's message if a constraint fails. This works just fine if the constraint failure was caused by user input. However, this doesn't account for cases where the browser itself triggers constraint validation, such as submitting a form.

It seems like the ideal solution would be to listen for invalid events and call setValidity in the event handler rather than in checkHtml5Validity.

Steps to reproduce

  1. Add a required OInput to a form:
    <form>
    <OField label="Name">
      <OInput required />
    </OField>
    <OButton>Submit</OButton>
    </form>
  2. Submit the form without ever focusing the name field.

Expected behavior

Constraint validation should prevent the form from being submitted, and the field should display an error message matching the failed validation constraint (e.g. "This field is required"), just like it would if you simply focused and blurred the element.

Actual behavior

The browser prevents form submission, and it focuses the empty field and displays its own constraint validation pop-up, but the OField doesn't display a message until the field loses focus.

blm768 commented 2 years ago

Another thing that seems a bit off with the current implementation is that checkHtml5Validity calls checkValidity, which may trigger invalid events. For "vanilla" HTML controls, invalid events are pretty much only triggered when the user tries to submit a form, which sort of suggests that checkValidity should mostly be called for events that "resemble" form submission — that is, we're about to make a logical decision (e.g. "do we let the user submit the form?") as a result of an explicit user action rather than just change a validation message. It may make sense to just inspect the validity.valid property on the input itself. That property updates "live" without triggering any side effects like events.

blm768 commented 2 years ago

If the decision is made that Oruga should move in this direction, I'd be willing to take on the implementation work.

jtommy commented 2 years ago

@blm768 you might work on it so I can review your PR

blm768 commented 2 years ago

I'll take a look. I think it'll be fairly straightforward, although there'll be a bit of boilerplate to sort out.

astagi commented 1 year ago

Thanks a lot @blm768 !