colinaut / alpinejs-plugin-simple-validate

Simple Alpine form validation plugin
97 stars 4 forks source link

Global error message for big forms #8

Closed kevinmu17 closed 1 year ago

kevinmu17 commented 1 year ago

Great plugin!

Is there any way to get an global error message within the form not linked to any field?

when having a very big form it can be unclear if 'nothing' happens within the viewport (most cases on mobile), so as a sort of fallback we want to create an error message around the submit button that toggles when something is wrong.

I now have something like this: x-data="{formValid: true}" on the form tag

<div class="error-msg" x-show="formValid === false">
    There is something wrong with the form, please check your input
</div>
<button type="submit" @click="formValid = $validate.isComplete($root)">Send</button>

This was a quick draft and i'm not liking this solution for the following reasons: 1: My naming isn't correct 2: no listeners when editing the form, so the error stays even if you have corrected all your errors 3: IMO this would be an awesome addition to this plugin

colinaut commented 1 year ago

If you use the $validate.submit then it should automatically move focus to the first field with an error, which should solve the issue of a long form. However if you want another error next to the submit button, you can accomplish this with a simple alpine script. Your example above is close but not quite:

<form x-validate x-data="{isSubmitPressed:false}" @submit="$validate.submit">
...
<div class="full-form-error-msg" x-show="isSubmitPressed && !$validate.isComplete($root)">
    There is something wrong with the form, please check your input
</div>
<button type="submit" @click="isSubmitPressed = true">Send</button>
</form>

This works as both isSubmitPressed and $validate.isComplete($root) are reactive so the full-form-error-msg will appear only if submit is pressed and the form is not complete. It will then disappear once all fields are complete.

It would actually be more complicated to implement this as part of the plugin than to just do it this way. The plugin does not currently track things like if the submit button has been pressed or not. I'm hesitant to add that as it would add bloat.

kevinmu17 commented 1 year ago

I totally missed the scrolling part in this plugin! Your solution works, but it's indeed not necessary due to the scrolling behaviour.

I'm hesitant to add that as it would add bloat.

Sure, i love that philosophy ;) lean and clean!

Thanks for the help!