An open API service indexing awesome lists of open source software.

https://github.com/markmead/alpinejs-form-validation

Adds client side form/input validation powered by Alpine JS ✅
https://github.com/markmead/alpinejs-form-validation

alpine-js alpinejs alpinejs-plugin form-validation javascript javascript-validation validation

Last synced: 3 months ago
JSON representation

Adds client side form/input validation powered by Alpine JS ✅

Awesome Lists containing this project

README

        

# Alpine JS Form Validation

Add client side form validation with Alpine JS 🎉

## Install

### With a CDN

```html

```

### With a Package Manager

```shell
yarn add -D alpinejs-form-validation

npm install -D alpinejs-form-validation
```

```js
import Alpine from 'alpinejs'
import validation from 'alpinejs-form-validation'

Alpine.plugin(validation)

Alpine.start()
```

## Example

_This example uses Tailwind CSS for styling but that is not mandatory._

```html


Name


Need a name


Age


Must be at least 18 years old


Can't be older than 24 years old


Message


Must be at least 10 characters


Can't be more than 50 characters



I accept the terms and conditions


Must accept


Submit

```

### Functionality

Breaking down the example we have the following.

#### `$dispatch('validate')`

Emitting the event `validate` will trigger each input within the element that
the event was emitted from to run through the validation checks.

#### `x-validation.required="contactName"`

Here we are setting up the directive `x-validation` and passing the modifier
`required` which says, the value of `contactName` must exist to pass validation.

**Validation Options**

- `required`
- `min.X` (Where "X" is an integer)
- `max.X` (Where "X" is an integer)
- `min:length.X` (Where "X" is an integer)
- `max:length.X` (Where "X" is an integer)

#### `@error="required = $valid($event.detail, 'required')"`

Here we have a few things going on.

We're listing for the `@error` event which is emitted once the input has run
through the validation checks. We're then setting `required` to either
true/false based on the response from the magic helper `$valid`.

**`$valid`**

This is a magic helper which returns true/false based on the validation status
of the input. You pass in the `$event.detail` which comes from the `@error`
event and the validation option, in the example that's `required`.

### Styling

You could style the inputs like this:

```css
[data-validation-valid='false'] {
border-color: red;
}

[data-validation-valid='true'] {
border-color: green;
}
```

### Stats

![](https://img.shields.io/bundlephobia/min/alpinejs-form-validation)
![](https://img.shields.io/npm/v/alpinejs-form-validation)
![](https://img.shields.io/npm/dt/alpinejs-form-validation)
![](https://img.shields.io/github/license/markmead/alpinejs-form-validation)