Nov 27, 2024
0
Level 1
Statamic Precognition form validation issue
I am trying to validate this form using the Statamic docs, however I am stuck and not sure how to proceed. I have alread installed laravel-precognition-alpine and imported it into the site.js
import Alpine from 'alpinejs';
import Precognition from 'laravel-precognition-alpine';
Alpine.plugin(Precognition);
Alpine.start();
This is the form that when I try to submit it empty, or with data populated it prompts 422 (Unprocessable Content) as well as AxiosError {message: 'Request failed with status code 422', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
{{ form handle="{selected_form:handle}" attr:x-ref="form" js="alpine" novalidate="novalidate" }}
<div x-data='{
form: $form(
"post",
$refs.form.getAttribute("action"),
JSON.parse($refs.form.getAttribute("x-data"))
),
init() {
$refs.form.addEventListener("submit", evt => {
evt.preventDefault();
this.form.submit().then(response => {
this.form.reset();
console.log("Success")
}).catch(error => {
console.log(error);
});
});
}
}'>
{{if success}}
<p x-show="success" class="text-orange-dark font-bold mb-4">
Thanks! Someone will be in touch soon.
</p> {{/if}}
<div class="form_field-page flex flex-col pt-4 pb-4 gap-4 w-full">
<input type="hidden" name="honeypot">
{{fields}}
<div>
{{ field }}
<small x-show="form.invalid('{{ handle }}')" x-text="form.errors.{{ handle }}" class="text-red-400"></small>
</div>
{{/fields}}
</div>
<button
type="submit"
class="cta_button"
:disabled="form.processing"
>
Contact
</button>
</div>
{{ /form }}
However if I use plain object, then it only prompts the 422 response for an empty form, and saves the data.
x-data="{
form: $form(
'post',
$refs.form.getAttribute('action'),
JSON.parse($refs.form.getAttribute('x-data'))
).setErrors([]),
init() {
$refs.form.addEventListener('submit', evt => {
evt.preventDefault();
const formData = new FormData($refs.form);
const plainData = {};
formData.forEach((value, key) => {
plainData[key] = value;
});
this.form.submit({ data: plainData })
.then(response => {
this.form.reset();
console.log('Success:', response);
})
.catch(error => {
if (error.response && error.response.data.errors) {
this.form.setErrors(error.response.data.errors);
} else {
console.error('Unexpected error:', error);
}
});
});
}
}"
Please or to participate in this conversation.