Instant form validation feedback is now an expectation, but pulling in a full toolchain to get it is often overkill for a small static site or a server-rendered Rails or Laravel app. Alpine.js and Iodine.js provide that interactivity with only a negligible page-load cost and little technical debt, and neither requires a build step. The two APIs are easiest to understand by building the validation up in stages, starting from a plain-JavaScript baseline.
The two libraries
Iodine is a micro form validation library from Matt Kingshott. It validates a single value against multiple rules and returns sensible messages when a rule fails. Alpine is a CDN-delivered, dependency-free library that weighs only 8.36 KB minified and gzipped — roughly a fifth of a create-react-app hello world — and is documented entirely by a GitHub README. As Hugo Di Francesco puts it:
Alpine.js is a Vue template-flavored replacement for jQuery and vanilla JavaScript rather than a React/Vue/Svelte/WhateverFramework competitor.
A vanilla Iodine baseline
Iodine can be loaded from a CDN:
<script src="https://cdn.jsdelivr.net/gh/mattkingshott/iodine@3/dist/iodine.min.js" defer></script>
or imported through Skypack:
import kingshottIodine from "https://cdn.skypack.dev/@kingshott/iodine";
When importing from Skypack, import kingshottIodine. The library still registers Iodine on the global scope, so user code keeps that name.
Validation centres on Iodine.is(value, rules), where the second argument is an array of rule strings. The method returns true on success, or a string naming the failed rule — so a strict comparison (=== true) is mandatory, since JavaScript otherwise treats the message string as truthy. Rules can live next to each input as JSON in a data attribute. That pattern isn't built into either library, but it co-locates inputs with their constraints; the attribute needs single quotes around it and double quotes inside to stay valid JSON.
<input name="email" type="email" id="email" data-rules='["required","email"]'>
A submit handler walks the DOM and calls Iodine with each element's value and the JSON.encode() result of that input's dataset.rules:
let form = document.getElementById("form");
// This is a nice way of getting a list of checkable input elements
// And converting them into an array so we can use map/filter/reduce functions:
let inputs = [...form.querySelectorAll("input[data-rules]")];
function onSubmit(event) {
inputs.map((input) => {
if (Iodine.is(input.value, JSON.parse(input.dataset.rules)) !== true) {
event.preventDefault();
input.classList.add("invalid");
}
});
}
form.addEventListener("submit", onSubmit);
The result is a poor user experience. Nothing tells the user what is wrong, problems surface only at submit time, and the invalid class sticks to inputs even after they have been corrected.
Adding Alpine for live feedback
Alpine loads from a CDN, or via Skypack import:
<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js" defer></script>
import alpinejs from "https://cdn.skypack.dev/alpinejs";
A natural timing rule is to validate an input once it is blurred, then on every change afterwards. That avoids scolding the user mid-typing while still reacting immediately to corrections.
Each input needs two pieces of state: whether it has been blurred, and its error message (an absent message means the input is valid). Alpine holds such state in a component declared with x-data on a parent element, readable and mutable by children. For cleaner HTML, declare a function that returns the data and methods, register it with Alpine.data, then call Alpine.start(). Registering a function also makes the logic reusable across components and projects. The component starts with an entry per field, keyed by the input's name attribute, holding errorMessage as an empty string and blurred as a boolean:
<form id="form" x-data="form" action="">
<h1>Log In</h1>
<label for="username">Username</label>
<input name="username" id="username" type="text" data-rules='["required"]'>
<label for="email">Email</label>
<input name="email" type="email" id="email" data-rules='["required","email"]'>
<label for="password">Password</label>
<input name="password" type="password" id="password" data-rules='["required","minimum:8"]'>
<label for="passwordConf">Confirm Password</label>
<input name="passwordConf" type="password" id="passwordConf" data-rules='["required","minimum:8"]'>
<input type="submit">
</form>
Alpine.data("form", form);
Alpine.start();
function form(){
return {
username: {errorMessage:'', blurred:false},
email: {errorMessage:'', blurred:false},
password: {errorMessage:'', blurred:false},
passwordConf: {errorMessage:'', blurred:false},
}
}
An x-bind:class on each input applies invalid when the field has blurred and a message exists:
<input name="username" id="username" type="text"
x-bind:class="{'invalid':username.errorMessage && username.blurred}" data-rules='["required"]'>
Wiring the events
Alpine handles events through x-on or, as in Vue, the @ shorthand; both behave identically. On input, the component's errorMessage is set to a message when the value is invalid and an empty string otherwise. On blur, the field's blurred flag is set to true and the error message is recalculated, so the initialised blank string is never what gets displayed. Two more methods on the object returned by form() handle both events, using the event target's name to find the right slice of component data:
<input
name="username" id="username" type="text"
x-bind:class="{'invalid':username.errorMessage && username.blurred}"
@blur="blur" @input="input"
data-rules='["required"]'
>
function form(){
return {
username: {errorMessage:'', blurred:false},
email: {errorMessage:'', blurred:false},
password:{ errorMessage:'', blurred:false},
passwordConf: {errorMessage:'', blurred:false},
blur: function(event) {
let ele = event.target;
this[ele.name].blurred = true;
let rules = JSON.parse(ele.dataset.rules)
this[ele.name].errorMessage = this.getErrorMessage(ele.value, rules);
},
input: function(event) {
let ele = event.target;
let rules = JSON.parse(ele.dataset.rules)
this[ele.name].errorMessage = this.getErrorMessage(ele.value, rules);
},
getErrorMessage: function() {
// to be completed
}
}
}
Producing and displaying messages
getErrorMessage returns an empty string when Iodine.is yields true; otherwise it hands the failing rule to Iodine's getErrorMessage method, which returns a human-readable string:
getErrorMessage:function(value, rules){
let isValid = Iodine.is(value, rules);
if (isValid !== true) {
return Iodine.getErrorMessage(isValid);
}
return '';
}
Below each input, a <p> with an error-message class is shown only when a message exists. x-show toggles display: none; according to whether a JavaScript expression resolves to true, reusing the same expression as the class binding; x-text binds the element's inner text to the component state:
<p x-show="username.errorMessage && username.blurred" x-text="username.errorMessage" class="error-message"></p>
Submission moves to @submit on the form, calling a submit method. Alpine's $el refers to the parent element holding the component state, which avoids longer DOM lookups:
<form id="form" x-data="form" @submit="submit" action="">
<!-- inputs... -->
</form>
submit: function (event) {
let inputs = [...this.$el.querySelectorAll("input[data-rules]")];
inputs.map((input) => {
if (Iodine.is(input.value, JSON.parse(input.dataset.rules)) !== true) {
event.preventDefault();
}
});
}
At this point the form corrects itself in real time, reports problems before submission but only after a blur, and refuses to submit while any field is invalid.
Server-rendered apps: surfacing backend errors
Client-side rules cannot cover everything — an email address may already be in use, or validity may depend on a complicated database record. The lightweight route is to ship server-side errors on each input as another JSON data attribute. An x-init function runs when the component initialises; it lifts those errors from the DOM into each input's component data, and getErrorMessage is updated to return server errors first and fall back to client-side checks:
<input name="username" id="username" type="text"
x-bind:class="{'invalid':username.errorMessage && username.blurred}"
@blur="blur" @input="input" data-rules='["required"]'
data-server-errors='["Username already in use"]'>
Because a server error should disappear once the user starts fixing the field, the stored array is replaced with an empty one whenever that input changes:
init: function () {
this.inputElements = [...this.$el.querySelectorAll("input[data-rules]")];
this.initDomData();
},
initDomData: function () {
this.inputElements.map((ele) => {
this[ele.name] = {
serverErrors: JSON.parse(ele.dataset.serverErrors),
blurred: false
};
});
}
Cross-field rules
Some inputs are only valid relative to others: a password confirmation against its password, or a job start date that must fall after a date of birth. The fix is to recompute every input's state on every input and blur event, so interdependent fields never read stale data. A matchingPassword rule, created with Iodine's addRule method, exercises this:
Iodine.addRule(
"matchingPassword",
value => value === document.getElementById("password").value
);
A custom message is registered by adding a key to Iodine's messages property:
Iodine.messages.matchingPassword="Password confirmation needs to match password";
Both calls belong in init. Before this change, editing the password field left the confirmation field unaware; now every change rechecks the whole form and the two always agree.
Cleanup and reuse
Three refinements shrink the code. First, have getErrorMessage return a message only when the input has blurred, so the class binding checks a single value:
x-bind:class="{'invalid':username.errorMessage}"
and the mapping functions set errorMessage accordingly:
updateErrorMessages: function () {
// Map through the input elements and set the 'errorMessage'
this.inputElements.map((ele) => {
this[ele.name].errorMessage = this.getErrorMessage(ele);
});
},
getErrorMessage: function (ele) {
// Return any server errors if they're present
if (this[ele.name].serverErrors.length > 0) {
return this[ele.name].serverErrors[0];
}
// Check using Iodine and return the error message only if the element has not been blurred
const error = Iodine.is(ele.value, JSON.parse(ele.dataset.rules));
if (error !== true && this[ele.name].blurred) {
return Iodine.getErrorMessage(error);
}
// Return empty string if there are no errors
return "";
},
Second, move the listeners off individual inputs and onto the parent form. Note that blur does not bubble, so a parent listener never fires for child blurs; substitute focusout, the same event but one that bubbles.
Third, generate the initial component data inside init by mapping over the form's inputs that carry a data-rules attribute. Renaming a field no longer means rewriting the data object, and adding another form takes just the script plus the rule attributes.
Finally, a fade-in transition from Alpine draws attention to the error text:
<p class="error-message" x-show="username.errorMessage" x-text="username.errorMessage" x-transition:enter></p>
The finished form function can be copied wholesale; only the HTML attributes need configuring to apply it to another form.



