colinaut / alpinejs-plugin-simple-validate

Simple Alpine form validation plugin
97 stars 4 forks source link

If plugin is bundled, it doesn't seem to start #6

Closed aroncal closed 1 year ago

aroncal commented 1 year ago

Hi:

I have an Alpine project and wanted to include this plugin to validate forms. I've followed bundling instructions here:

https://github.com/colinaut/alpinejs-plugin-simple-validate#bundling-and-initializing

But it doesn't seem to start the plugin (no spans for the error messages or aria attributes for invalid states are added), and neither any error arises on the console. The relevant parts of my code are:

index.js

import Alpine from 'alpinejs';
import validate from '@colinaut/alpinejs-plugin-simple-validate';
Alpine.plugin(validate);
window.Alpine = Alpine;
Alpine.start();

index.html (I don't include any JS in the because webpack takes care of bundling and inserting the bundle)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <form @change="wanted.dirty = true" x-data x-validate>
    <input type="text" x-model="wanted.nombre" required>
  </form>
</body>
</html>

Am I missing something? Thanks

colinaut commented 1 year ago

You've got a couple problems here:

  1. It's probably failing because Alpine is looking for a variable called wanted which doesn't exist anywhere in your code. I'm sure if you check your console log it will show that error. AlpineJS is fragile like that. If you are having it use a variable that does not exist then it will break everything.
  2. x-validate requires a name or id attribute on the input/textarea/select elements. Without which x-validate will just ignore it and not set up the error msg.

I just added examples-bundled to the repository to show that it works bundled.

aroncal commented 1 year ago

Thanks for the clarification and for the examples-bundled. I was missing the id/name attribute on the required field, I missed that on the documentation. I didn't have any problem with the variable "wanted": I just put here a reduced version of my code for clarity. Thanks again.