colinaut / alpinejs-plugin-simple-validate

Simple Alpine form validation plugin
102 stars 4 forks source link

The documentation lacks a simple example #31

Closed borgogelli closed 2 months ago

borgogelli commented 2 months ago

I think it would be useful to have a simple example with validation and subsequent call of a custom function.

I use the following working code but I don't know if it's the better solution.

<script>
document.addEventListener("alpine:init", () => {
  Alpine.data("myForm", () => ({
    myForm() {},
    async postData(validated, formData) {
        if(validated){
            console.log('formData:  ' + JSON.stringify(formData));
        }
    },
  }));
});
</script>
<form id="form" x-data="myForm" x-validate.validate-on-submit @submit.prevent="postData($validate.isComplete('form'), $formData)">
....

I'm lost.

colinaut commented 2 months ago

You've basically got it. Easier is just to embed the check directly in the @submit. Note if you only need to post the simple object with {key: value} rather than the entire x-validate formData then use $validate.value('form'). This is what I would use.

<form 
  id="form" 
  x-data="myForm" 
  x-validate.validate-on-submit 
  @submit.prevent="if ($validate.isComplete('form')) postData($validate.value('form'))" >

Also unless you really need to submit via javascript, you could just use normal HTML form submit method. The x-validate.validate-on-submit works great with this approach. If it hits a validation issue, it stops and if not then it submits like normal.

<form 
  id="form" 
  x-data="myForm" 
  x-validate.validate-on-submit 
  method="post"
action="/api/post-form-endpoint"
>

I'll add examples in the README.

colinaut commented 2 months ago

Added example to README

borgogelli commented 2 months ago

@colinaut thank you very much 👍