AJAX Login Form
AJAX Login Form
A common login flow validates the form before sending any network request. If every field passes validation, the form is submitted using AJAX without refreshing the page.
This example validates an email address and password, sends the login request to /api/login, then redirects the user after a successful response.
HTML
<form id="loginForm">
<input
type="email"
name="email"
required
/>
<input
type="password"
name="password"
required
minlength="8"
/>
<button type="submit">
Log in
</button>
</form>
JavaScript
import NFSFU234FormValidation from "@nfsfu234/form-validation";
const validator = new NFSFU234FormValidation({
form: "loginForm"
});
const form = document.getElementById("loginForm");
form.addEventListener("submit", async (event) => {
event.preventDefault();
const result = await validator.submit({
isAjax: true,
ajaxOptions: {
url: "/api/login",
RequestMethod: "POST",
RequestHeader: {
"Content-Type": "application/json"
}
}
});
if (result.type === "success") {
window.location.href = "/dashboard";
return;
}
validator.displayError(result);
});
What happens?
When the user clicks Log in, NFSFU234FormValidation performs the following steps:
- Validates every field in the form.
- Stops immediately if any field fails validation.
- Displays validation errors.
- Builds the request body from the form values.
- Sends an AJAX request to
/api/login. - Returns the server response.
- Redirects the user after a successful login.
No page refresh occurs during the process.
Why no validation rules?
This form already uses native HTML validation attributes.
<input
type="email"
required
/>
<input
type="password"
required
minlength="8"
/>
The library automatically reads attributes such as:
requiredtypeminlengthmaxlengthpatternminmax
No additional configuration is needed for simple forms.
AJAX configuration
AJAX is enabled by passing isAjax: true to submit() together with an ajaxOptions object.
await validator.submit({
isAjax: true,
ajaxOptions: {
url: "/api/login",
RequestMethod: "POST"
}
});
Supported options include:
ajaxOptions: {
url: "/api/login",
RequestMethod: "POST",
RequestHeader: {
"Content-Type": "application/json"
}
}
The request body is generated automatically from the form fields.
Returning JSON
A typical successful response might look like this.
{
"success": true,
"token": "...",
"user": {
"id": 1,
"name": "John Doe"
}
}
An unsuccessful response could be:
{
"success": false,
"message": "Invalid email or password."
}
Use the object returned by submit() to determine what happens next in your application.
Continue learning
- 📡 AJAX Requests — Learn how the library sends HTTP requests.
- 🎨 Custom Error Messages — Customize validation feedback.
- 🔐 Password Utilities — Generate and evaluate secure passwords.
- ⚙️ Form Configuration — Configure validation entirely in JavaScript.
- 📚 Available Functions — Explore the complete API reference.