Written by: Geoffrey Callaghan

Svelte-forms-lib tutorial

Svelte-Forms-Lib Tutorial

Alpine.js, while primarily known for its reactivity in managing UI state and interactions, doesn’t have built-in form validation like some other frameworks or libraries. However, you can still implement form validation using Alpine.js along with HTML attributes and Alpine.js directives.

Here’s a simple example of how you can perform form validation using Alpine.js:

<div x-data="{ errors: {} }">
    <form @submit.prevent="submitForm">
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" x-model="name" @input="validateName">
            <p x-text="errors.name" class="error"></p>
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" x-model="email" @input="validateEmail">
            <p x-text="errors.email" class="error"></p>
        </div>
        <button type="submit">Submit</button>
    </form>
</div>

<script>
    function isValidEmail(email) {
        // Basic email validation
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    Alpine.data('formValidation', () => ({
        name: '',
        email: '',
        errors: {},

        validateName() {
            if (!this.name.trim()) {
                this.errors.name = 'Name is required';
            } else {
                this.errors.name = '';
            }
        },

        validateEmail() {
            if (!this.email.trim()) {
                this.errors.email = 'Email is required';
            } else if (!isValidEmail(this.email)) {
                this.errors.email = 'Invalid email address';
            } else {
                this.errors.email = '';
            }
        },

        submitForm() {
            this.validateName();
            this.validateEmail();

            // Check if there are any errors
            if (Object.values(this.errors).every(error => !error)) {
                // Form is valid, submit the form or perform other actions
                console.log('Form submitted');
            } else {
                // Form is invalid, display error messages
                console.log('Form contains errors');
            }
        }
    }));
</script>

In this example:

  • We use Alpine.js to manage the form state and validation errors.
  • Each input field is bound to a property in the Alpine.js component using x-model.
  • We define validation functions for each input field (validateName and validateEmail) that update the errors object accordingly.
  • The form submission is handled by the submitForm function, which triggers validation for each field and checks if there are any errors before submitting the form or displaying error messages.

This is a basic example of form validation using Alpine.js. You can extend it further based on your specific requirements and validation logic. Additionally, you may also explore third-party Alpine.js plugins or libraries that provide more advanced form validation features.