Skip to content

Instantly share code, notes, and snippets.

@kidino
Created November 22, 2025 03:06
Show Gist options
  • Select an option

  • Save kidino/aedca1eae078d02a0db0efb6ea3161ad to your computer and use it in GitHub Desktop.

Select an option

Save kidino/aedca1eae078d02a0db0efb6ea3161ad to your computer and use it in GitHub Desktop.
Firaform - Displaying Form Validation Errors
<html>
<head>
<title>Form Error</title>
</head>
<body>
<div id="form-errors" aria-live="polite"></div>
</body>
<script>
// Get message/errors from URL and show in #form-errors container
(function () {
const qs = new URLSearchParams(window.location.search);
if (qs.get('status') !== 'error') return;
const message = qs.get('message') ? decodeURIComponent(qs.get('message')) : 'An error occurred.';
const errorsRaw = qs.get('errors');
let errors = [];
if (errorsRaw) {
try {
errors = JSON.parse(decodeURIComponent(errorsRaw));
if (!Array.isArray(errors)) errors = [String(errors)];
} catch {
errors = [String(errorsRaw)];
}
}
const container = document.getElementById('form-errors');
if (!container) return;
// safe escaping
const escape = str => String(str)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
let html = `<div class="text-red-700 bg-red-50 border border-red-200 p-4 rounded"><strong>${escape(message)}</strong>`;
if (errors.length) {
html += '<ul class="mt-2 list-disc ml-5">';
html += errors.map(e => `<li>${escape(e)}</li>`).join('');
html += '</ul>';
}
html += '</div>';
container.innerHTML = html;
// remove query params to avoid repeat display
window.history.replaceState({}, document.title, window.location.pathname + window.location.hash);
})();
</script>
</html>
<?php
// Read query params safely
$status = isset($_GET['status']) ? $_GET['status'] : null;
if ($status === 'error') {
$message = isset($_GET['message']) ? $_GET['message'] : 'An error occurred.';
$errorsJson = isset($_GET['errors']) ? $_GET['errors'] : '[]';
// Decode URL-encoded JSON list of errors
$errors = json_decode(urldecode($errorsJson), true);
if (!is_array($errors)) {
$errors = [];
}
?>
<div class="alert alert-danger p-4 rounded">
<strong><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></strong>
<?php if (!empty($errors)) : ?>
<ul class="mt-2 list-disc ml-5">
<?php foreach ($errors as $err) : ?>
<li><?= htmlspecialchars($err, ENT_QUOTES, 'UTF-8') ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
<?php
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment