@blo4r/x-validate v0.1.3
Alpine Validate
Many forms require basic validation, and using native form validation can be sufficient. However, customizing the appearance of these forms can be challenging.
The AlpineJS "validate" directive offers a solution to this issue by allowing you to display error messages in a clear and concise manner. This directive utilizes the native API to provide seamless integration with your existing form elements, making it an efficient and straightforward solution for client-side form validation.
Installation
CDN
To be done
NPM
npm install @blo4r/alpine-validate
Add the x-validate
directive to your project by registering the plugin with Alpine.
import Alpine from "alpinejs"
import { Validate } from "@blo4r/alpine-validate"
Alpine.plugin(Validate)
window.Alpine = Alpine
window.Alpine.start()
Usage
Display native validation messages
<form x-data x-validate>
<div x-data="{error: ''}" @validation="error = $event.detail.error">
<input type="email" name="email" id="email" required />
<div x-text="error"></div>
</div>
</form>
Customize native validation messages
<form x-data x-validate>
<div x-data="{error: ''}" @validation="error = $event.detail.error">
<input
type="email"
name="email"
id="email"
required
x-validate:messages="{
valueMissing: 'You forgot to enter your email address! 😅',
typeMismatch: 'This appears to be an invalid email address. 👀'
}"
/>
<div x-text="error"></div>
</div>
</form>
Add custom controls and messsages
<script>
const morethan5 = (value) => value.length > 4
</script>
<form x-data x-validate>
<div x-data="{error: ''}" @validation="error = $event.detail.error">
<input
type="email"
name="email"
id="email"
required
x-validate:controls="morethan5"
x-validate:messages="{morethan5: 'Provide a value longer than 5 caracter'}"
/>
<div x-text="error"></div>
</div>
</form>
Modifiers
x-validate
provide two modifiers.
Modifier | Description | Usage |
---|---|---|
x-validate:messages | Change the native message error | x-validate:messages="{<error_name>: <error text>, ...}" |
x-validate:controls | Add custom controls | x-form:controls="[<custom control function name>]" |
Versioning
This projects follow the Semantic Versioning guidelines.
License
Copyright (c) 2023 Julien Lopinto and contributors
Licensed under the MIT license, see LICENSE.md for details.