Embed code
The Embed code holds your form as JSON in a data-wds-form element, plus one script tag. When the page loads, the script turns the JSON into the form, so there is no script of your own to write and it works with a strict Content Security Policy. This is the code for the contact form in the examples:
<!-- Contact us: made with WDS Forms, https://webdevsnippets.com/wds-forms -->
<!-- Bootstrap 5 CSS: leave this out if your page already loads it -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css">
<div data-wds-form data-theme="bootstrap5">
<script type="application/json">
{
"version": 1,
"title": "Contact us",
"description": "We usually answer within one working day.",
"fields": [
{
"id": "f1",
"type": "text",
"name": "name",
"label": "Name",
"required": true,
"width": 6,
"autocomplete": "name"
},
{
"id": "f2",
"type": "email",
"name": "email",
"label": "Email",
"required": true,
"width": 6,
"autocomplete": "email"
},
{
"id": "f3",
"type": "select",
"name": "topic",
"label": "Topic",
"placeholder": "Choose…",
"required": true,
"options": [
{
"label": "Sales",
"value": "sales"
},
{
"label": "Support",
"value": "support"
},
{
"label": "Other",
"value": "other"
}
]
},
{
"id": "f4",
"type": "text",
"name": "order",
"label": "Order number",
"placeholder": "WDS-12345",
"required": true,
"pattern": "WDS-\\d{5}",
"patternMessage": "Use the format WDS-12345.",
"showIf": {
"logic": "all",
"rules": [
{
"field": "topic",
"op": "eq",
"value": "support"
}
]
}
},
{
"id": "f5",
"type": "textarea",
"name": "message",
"label": "Message",
"rows": 5,
"required": true,
"minLength": 10,
"maxLength": 2000
},
{
"id": "f6",
"type": "file",
"name": "attachment",
"label": "Attachment",
"accept": ".pdf,.jpg,.png",
"maxSize": 5,
"help": "PDF, JPG or PNG, up to 5 MB."
},
{
"id": "f7",
"type": "checkbox",
"name": "privacy",
"label": "I agree that my message is stored to answer it",
"required": true
}
],
"settings": {
"action": "/contact",
"submitText": "Send message",
"successMessage": "Thank you! We will answer within one working day."
}
}
</script>
</div>
<!-- WDS Forms (free, MIT): turns the JSON above into the form, checks it and sends it -->
<script src="https://cdn.jsdelivr.net/npm/wds-forms@1/dist/wds-forms.min.js" defer></script>
Paste it into any page: plain HTML, WordPress (in a Custom HTML block), Razor, Blade, React or a site builder that accepts HTML. If your page already loads Bootstrap, leave out the stylesheet line.
Sending the answers
Set the address in Get code (Send the answers to) or in the form settings. The form sends to it without leaving the page: as form data with the uploaded files, or as JSON when Send as is JSON. While it sends, the button is disabled; then the form shows your thank-you message and clears itself. Your server replies like this, and the server code does it for you:
200 OK { "ok": true } the form shows its thank-you message
422 Unprocessable Content { "errors": { "email": "…" } } the messages appear at the fields
any other status the form shows its error message
Fields hidden by a condition are not sent. A form on another domain than its server needs CORS headers on the server.
Server code: PHP, Node.js, ASP.NET Core and Python
The Server code in the builder is made for your form. It reads the answers (form data, files and JSON), checks every field again with the same rules as the browser, skips the fields hidden by their conditions, accepts only the listed options and file types, and replies with { "ok": true } or 422 { "errors": … }. A form sent without JavaScript gets a small page instead. The comment The answers are valid marks where to save or email them. This is the code for the contact form above:
One file for PHP 8 or later, no framework and no Composer packages. Upload it and send the form to its address, for example /form-handler.php.
<?php
// Form handler for "Contact us", made with WDS Forms (https://webdevsnippets.com/wds-forms).
// It checks every answer again on the server (never trust the browser alone), then replies with JSON for the
// WDS Forms script, or with a small page for forms sent without JavaScript. Needs PHP 8 or later.
declare(strict_types=1);
const FIELDS = [
['name' => 'name', 'type' => 'text', 'label' => 'Name', 'required' => true],
['name' => 'email', 'type' => 'email', 'label' => 'Email', 'required' => true],
['name' => 'topic', 'type' => 'select', 'label' => 'Topic', 'required' => true, 'options' => ['sales', 'support', 'other']],
['name' => 'order', 'type' => 'text', 'label' => 'Order number', 'required' => true, 'pattern' => 'WDS-\\d{5}', 'patternMessage' => 'Use the format WDS-12345.', 'showIf' => ['logic' => 'all', 'rules' => [['field' => 'topic', 'op' => 'eq', 'value' => 'support']]]],
['name' => 'message', 'type' => 'textarea', 'label' => 'Message', 'required' => true, 'minLength' => 10, 'maxLength' => 2000],
['name' => 'attachment', 'type' => 'file', 'label' => 'Attachment', 'accept' => '.pdf,.jpg,.png', 'maxSize' => 5],
['name' => 'privacy', 'type' => 'checkbox', 'label' => 'I agree that my message is stored to answer it', 'required' => true]
];
const MESSAGES = [
'required' => 'This field is required.',
'requiredCheck' => 'Please check this box.',
'requiredChoice' => 'Please choose an option.',
'requiredFile' => 'Please choose a file.',
'email' => 'Enter a valid email address.',
'url' => 'Enter a valid web address, starting with http:// or https://.',
'tel' => 'Enter a valid phone number.',
'number' => 'Enter a number.',
'min' => 'Enter {min} or more.',
'max' => 'Enter {max} or less.',
'minDate' => 'Choose {min} or later.',
'maxDate' => 'Choose {max} or earlier.',
'minLength' => 'Enter at least {min} characters.',
'maxLength' => 'Enter at most {max} characters.',
'pattern' => 'The value is not in the expected format.',
'fileSize' => 'Each file must be {max} MB or smaller.',
'fileType' => 'This file type is not allowed.',
'success' => 'Thank you! We will answer within one working day.',
'fix' => 'Please correct these fields:',
'back' => 'Go back to the form'
];
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit;
}
$values = wdsf_values();
$visible = wdsf_visible($values);
$values = array_intersect_key($values, array_flip($visible)); // fields hidden by their conditions are left out
$errors = wdsf_validate($values, $visible);
$wantsJson = str_contains($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json');
if ($errors) {
http_response_code(422);
if ($wantsJson) {
header('Content-Type: application/json');
echo json_encode(['errors' => $errors]);
} else {
wdsf_page('<p>' . htmlspecialchars(MESSAGES['fix']) . '</p><ul>' . implode('', array_map(
fn ($name, $error) => '<li>' . htmlspecialchars(wdsf_label($name) . ': ' . $error) . '</li>',
array_keys($errors),
$errors
)) . '</ul>');
}
exit;
}
// ---------- The answers are valid: save them or email them here. ----------
// $values holds the answers by field name. wdsf_summary($values) gives them as "Label: answer" lines.
// Email them to yourself (needs a working mail setup on your server):
// mail('you@example.com', 'New form: Contact us', wdsf_summary($values));
// Keep an uploaded file (make the uploads folder first, outside the web root if you can):
// foreach ($values['attachment'] as $file) {
// move_uploaded_file($file['tmp_name'], __DIR__ . '/uploads/' . bin2hex(random_bytes(8)) . '-' . basename($file['name']));
// }
if ($wantsJson) {
header('Content-Type: application/json');
echo json_encode(['ok' => true]);
} else {
wdsf_page('<p>' . htmlspecialchars(MESSAGES['success']) . '</p>');
}
// ---------- WDS Forms helpers ----------
function wdsf_values(): array
{
$json = str_contains($_SERVER['CONTENT_TYPE'] ?? '', 'application/json');
$input = $json ? json_decode(file_get_contents('php://input') ?: 'null', true) : ($_SERVER['REQUEST_METHOD'] === 'GET' ? $_GET : $_POST);
$input = is_array($input) ? $input : [];
$values = [];
foreach (FIELDS as $f) {
$name = $f['name'];
$raw = $input[$name] ?? null; // PHP turns name[] into an array
if ($f['type'] === 'checkbox' || $f['type'] === 'switch') {
$values[$name] = $raw === true || in_array($raw, ['true', '1', 'on'], true);
} elseif ($f['type'] === 'file' && !$json) {
$values[$name] = wdsf_files($name);
} elseif (!empty($f['multiple'])) {
$values[$name] = array_values(array_filter(array_map('strval', array_filter((array) ($raw ?? []), 'is_scalar')), fn ($v) => $v !== ''));
} else {
$values[$name] = is_scalar($raw) ? trim((string) $raw) : '';
}
}
return $values;
}
function wdsf_files(string $name): array
{
$f = $_FILES[$name] ?? null;
if (!$f) {
return [];
}
$files = [];
foreach ((array) $f['name'] as $i => $fileName) {
$error = is_array($f['error']) ? $f['error'][$i] : $f['error'];
if ($error === UPLOAD_ERR_NO_FILE) {
continue;
}
$files[] = [
'name' => (string) $fileName,
'type' => (string) (is_array($f['type']) ? $f['type'][$i] : $f['type']),
'size' => $error === UPLOAD_ERR_OK ? (int) (is_array($f['size']) ? $f['size'][$i] : $f['size']) : PHP_INT_MAX,
'tmp_name' => (string) (is_array($f['tmp_name']) ? $f['tmp_name'][$i] : $f['tmp_name']),
'error' => $error,
];
}
return $files;
}
function wdsf_empty(mixed $value): bool
{
return $value === null || $value === '' || $value === false || $value === [];
}
function wdsf_fill(string $message, array $values): string
{
foreach ($values as $key => $value) {
$message = str_replace('{' . $key . '}', (string) $value, $message);
}
return $message;
}
function wdsf_check(array $f, mixed $value): ?string
{
$m = MESSAGES;
$type = $f['type'];
if ($type === 'hidden') {
return null;
}
if (wdsf_empty($value)) {
if (empty($f['required'])) {
return null;
}
return match ($type) {
'checkbox', 'switch' => $m['requiredCheck'],
'radio', 'checkboxes', 'select' => $m['requiredChoice'],
'file' => $m['requiredFile'],
default => $m['required'],
};
}
if ($type === 'file') {
foreach ($value as $file) {
if (!is_array($file)) {
continue;
}
if (!empty($f['maxSize']) && $file['size'] > $f['maxSize'] * 1024 * 1024) {
return wdsf_fill($m['fileSize'], ['max' => $f['maxSize']]);
}
if (!empty($f['accept']) && !wdsf_accepts($file, $f['accept'])) {
return $m['fileType'];
}
}
return null;
}
if (isset($f['options'])) { // a choice must be one of the options
foreach ((array) $value as $choice) {
if (!in_array((string) $choice, $f['options'], true)) {
return $m['requiredChoice'];
}
}
return null;
}
if (is_bool($value) || is_array($value)) {
return null;
}
$text = (string) $value;
switch ($type) {
case 'email':
if (!preg_match('/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/u', $text)) {
return $m['email'];
}
break;
case 'url':
if (!preg_match('~^https?://~i', $text) || filter_var($text, FILTER_VALIDATE_URL) === false) {
return $m['url'];
}
break;
case 'tel':
if (!preg_match('/^\+?[0-9\s().-]{5,20}$/', $text)) {
return $m['tel'];
}
break;
case 'number':
case 'range':
if (!is_numeric($text)) {
return $m['number'];
}
if (isset($f['min']) && (float) $text < (float) $f['min']) {
return wdsf_fill($m['min'], ['min' => $f['min']]);
}
if (isset($f['max']) && (float) $text > (float) $f['max']) {
return wdsf_fill($m['max'], ['max' => $f['max']]);
}
break;
case 'date':
case 'time':
if (isset($f['min']) && strcmp($text, $f['min']) < 0) {
return wdsf_fill($m['minDate'], ['min' => $f['min']]);
}
if (isset($f['max']) && strcmp($text, $f['max']) > 0) {
return wdsf_fill($m['maxDate'], ['max' => $f['max']]);
}
break;
}
$length = mb_strlen($text);
if (!empty($f['minLength']) && $length < $f['minLength']) {
return wdsf_fill($m['minLength'], ['min' => $f['minLength']]);
}
if (!empty($f['maxLength']) && $length > $f['maxLength']) {
return wdsf_fill($m['maxLength'], ['max' => $f['maxLength']]);
}
if (!empty($f['pattern'])) {
$ok = @preg_match('~^(?:' . str_replace('~', '\~', $f['pattern']) . ')$~u', $text);
if ($ok === 0) { // false means the pattern itself is broken: it is ignored
return $f['patternMessage'] ?? $m['pattern'];
}
}
return null;
}
function wdsf_accepts(array $file, string $accept): bool
{
$name = strtolower($file['name']);
$type = strtolower($file['type']);
foreach (explode(',', $accept) as $rule) {
$rule = strtolower(trim($rule));
if ($rule === '') {
continue;
}
if ($rule[0] === '.' ? str_ends_with($name, $rule) : (str_ends_with($rule, '/*') ? str_starts_with($type, substr($rule, 0, -1)) : $type === $rule)) {
return true;
}
}
return false;
}
function wdsf_rule(array $rule, mixed $value): bool
{
$expected = (string) ($rule['value'] ?? '');
$list = is_array($value) ? array_map(fn ($v) => is_array($v) ? (string) $v['name'] : (string) $v, $value) : null;
$text = match (true) {
$value === null => '',
$list !== null => implode(',', $list),
is_bool($value) => $value ? 'true' : 'false',
default => (string) $value,
};
$checked = $value === true || ($list !== null && count($list) > 0);
return match ($rule['op']) {
'eq' => $list !== null ? in_array($expected, $list, true) : $text === $expected,
'neq' => $list !== null ? !in_array($expected, $list, true) : $text !== $expected,
'contains' => $list !== null ? in_array($expected, $list, true) : str_contains(mb_strtolower($text), mb_strtolower($expected)),
'notContains' => $list !== null ? !in_array($expected, $list, true) : !str_contains(mb_strtolower($text), mb_strtolower($expected)),
'empty' => wdsf_empty($value),
'notEmpty' => !wdsf_empty($value),
'gt' => is_numeric($text) && is_numeric($expected) && (float) $text > (float) $expected,
'lt' => is_numeric($text) && is_numeric($expected) && (float) $text < (float) $expected,
'checked' => $checked,
'unchecked' => !$checked,
default => true,
};
}
function wdsf_shown(array $f, array $seen): bool
{
$rules = $f['showIf']['rules'] ?? [];
if (!$rules) {
return true;
}
$results = array_map(fn ($rule) => wdsf_rule($rule, $seen[$rule['field']] ?? null), $rules);
return ($f['showIf']['logic'] ?? 'all') === 'any' ? in_array(true, $results, true) : !in_array(false, $results, true);
}
/** The names of the fields shown for these answers (conditions can depend on each other). */
function wdsf_visible(array $values): array
{
$visible = array_column(FIELDS, 'name');
for ($pass = 0; $pass < 5; $pass++) {
$seen = array_intersect_key($values, array_flip($visible));
$next = array_column(array_filter(FIELDS, fn ($f) => wdsf_shown($f, $seen)), 'name');
if ($next === $visible) {
break;
}
$visible = $next;
}
return $visible;
}
function wdsf_validate(array $values, array $visible): array
{
$errors = [];
foreach (FIELDS as $f) {
if (!in_array($f['name'], $visible, true)) {
continue;
}
$error = wdsf_check($f, $values[$f['name']] ?? null);
if ($error !== null) {
$errors[$f['name']] = $error;
}
}
return $errors;
}
function wdsf_label(string $name): string
{
foreach (FIELDS as $f) {
if ($f['name'] === $name) {
return $f['label'];
}
}
return $name;
}
function wdsf_summary(array $values): string
{
$lines = [];
foreach ($values as $name => $value) {
$text = match (true) {
is_bool($value) => $value ? 'yes' : 'no',
is_array($value) => implode(', ', array_map(fn ($v) => is_array($v) ? $v['name'] : (string) $v, $value)),
default => (string) $value,
};
$lines[] = wdsf_label($name) . ': ' . $text;
}
return implode("\n", $lines);
}
function wdsf_page(string $body): void
{
$back = isset($_SERVER['HTTP_REFERER']) ? '<p><a href="' . htmlspecialchars($_SERVER['HTTP_REFERER']) . '">' . htmlspecialchars(MESSAGES['back']) . '</a></p>' : '';
header('Content-Type: text/html; charset=utf-8');
echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Form</title></head>';
echo '<body style="font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px">' . $body . $back . '</body></html>';
}
Express with multer for the uploads (npm install express multer). Files stay in memory; the comment shows how to save them.
// Form handler for "Contact us", made with WDS Forms (https://webdevsnippets.com/wds-forms).
// It checks every answer again on the server (never trust the browser alone), then replies with JSON for the
// WDS Forms script, or with a small page for forms sent without JavaScript.
// Node.js 18 or later: npm install express multer then: node form-handler.js
const express = require('express');
const multer = require('multer');
const FIELDS = [
{ name: 'name', type: 'text', label: 'Name', required: true },
{ name: 'email', type: 'email', label: 'Email', required: true },
{ name: 'topic', type: 'select', label: 'Topic', required: true, options: ['sales', 'support', 'other'] },
{ name: 'order', type: 'text', label: 'Order number', required: true, pattern: 'WDS-\\d{5}', patternMessage: 'Use the format WDS-12345.', showIf: { logic: 'all', rules: [{ field: 'topic', op: 'eq', value: 'support' }] } },
{ name: 'message', type: 'textarea', label: 'Message', required: true, minLength: 10, maxLength: 2000 },
{ name: 'attachment', type: 'file', label: 'Attachment', accept: '.pdf,.jpg,.png', maxSize: 5 },
{ name: 'privacy', type: 'checkbox', label: 'I agree that my message is stored to answer it', required: true }
];
const MESSAGES = {
required: 'This field is required.',
requiredCheck: 'Please check this box.',
requiredChoice: 'Please choose an option.',
requiredFile: 'Please choose a file.',
email: 'Enter a valid email address.',
url: 'Enter a valid web address, starting with http:// or https://.',
tel: 'Enter a valid phone number.',
number: 'Enter a number.',
min: 'Enter {min} or more.',
max: 'Enter {max} or less.',
minDate: 'Choose {min} or later.',
maxDate: 'Choose {max} or earlier.',
minLength: 'Enter at least {min} characters.',
maxLength: 'Enter at most {max} characters.',
pattern: 'The value is not in the expected format.',
fileSize: 'Each file must be {max} MB or smaller.',
fileType: 'This file type is not allowed.',
success: 'Thank you! We will answer within one working day.',
fix: 'Please correct these fields:',
back: 'Go back to the form'
};
const app = express();
const upload = multer({ limits: { fileSize: 25 * 1024 * 1024 } }); // files stay in memory
app.post('/contact', upload.any(), express.urlencoded({ extended: true }), express.json(), (req, res) => {
let values = readValues(req);
const visible = visibleFields(values);
values = Object.fromEntries(Object.entries(values).filter(([name]) => visible.has(name))); // hidden fields are left out
const errors = validate(values, visible);
const wantsJson = (req.get('accept') || '').includes('application/json');
if (Object.keys(errors).length) {
if (wantsJson) return res.status(422).json({ errors });
const items = Object.entries(errors).map(([name, error]) => '<li>' + escapeHtml(labelOf(name) + ': ' + error) + '</li>').join('');
return res.status(422).send(page('<p>' + escapeHtml(MESSAGES.fix) + '</p><ul>' + items + '</ul>', req));
}
// ---------- The answers are valid: save them or email them here. ----------
// values holds the answers by field name; summary(values) gives them as "Label: answer" lines,
// for example for an email with nodemailer (npm install nodemailer).
// Uploaded files are in memory: values.attachment is a list of { originalname, mimetype, size, buffer }.
// Save one with: require('node:fs').writeFileSync('uploads/' + Date.now() + '-' + file.originalname.replace(/[^\w.-]/g, '_'), file.buffer);
if (wantsJson) return res.json({ ok: true });
res.send(page('<p>' + escapeHtml(MESSAGES.success) + '</p>', req));
});
app.listen(3000, () => console.log('Form handler on http://localhost:3000/contact'));
// ---------- WDS Forms helpers ----------
function readValues(req) {
const body = req.body && typeof req.body === 'object' ? req.body : req.query;
const json = req.is('application/json');
const values = {};
for (const f of FIELDS) {
const raw = body[f.name] !== undefined ? body[f.name] : body[f.name + '[]'];
if (f.type === 'checkbox' || f.type === 'switch') {
values[f.name] = raw === true || raw === 'true' || raw === '1' || raw === 'on';
} else if (f.type === 'file' && !json) {
values[f.name] = (req.files || []).filter((file) => file.fieldname === f.name || file.fieldname === f.name + '[]');
} else if (f.multiple) {
values[f.name] = [].concat(raw === undefined || raw === null ? [] : raw).filter((v) => typeof v !== 'object').map(String).filter((v) => v !== '');
} else {
values[f.name] = typeof raw === 'string' || typeof raw === 'number' ? String(raw).trim() : '';
}
}
return values;
}
const isEmpty = (v) => v === undefined || v === null || v === '' || v === false || (Array.isArray(v) && v.length === 0);
const fill = (text, values) => text.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ''));
function check(f, value) {
const m = MESSAGES;
if (f.type === 'hidden') return null;
if (isEmpty(value)) {
if (!f.required) return null;
if (f.type === 'checkbox' || f.type === 'switch') return m.requiredCheck;
if (f.type === 'radio' || f.type === 'checkboxes' || f.type === 'select') return m.requiredChoice;
if (f.type === 'file') return m.requiredFile;
return m.required;
}
if (f.type === 'file') {
for (const file of value) {
if (!file || typeof file !== 'object') continue;
if (f.maxSize && file.size > f.maxSize * 1024 * 1024) return fill(m.fileSize, { max: f.maxSize });
if (f.accept && !accepts(file, f.accept)) return m.fileType;
}
return null;
}
if (f.options) {
// a choice must be one of the options
return [].concat(value).every((choice) => f.options.includes(String(choice))) ? null : m.requiredChoice;
}
if (typeof value === 'boolean' || Array.isArray(value)) return null;
const text = String(value);
switch (f.type) {
case 'email':
if (!/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/.test(text)) return m.email;
break;
case 'url':
try {
if (!['http:', 'https:'].includes(new URL(text).protocol)) return m.url;
} catch {
return m.url;
}
break;
case 'tel':
if (!/^\+?[0-9\s().-]{5,20}$/.test(text)) return m.tel;
break;
case 'number':
case 'range': {
const n = Number(text);
if (Number.isNaN(n)) return m.number;
if (f.min !== undefined && n < Number(f.min)) return fill(m.min, { min: f.min });
if (f.max !== undefined && n > Number(f.max)) return fill(m.max, { max: f.max });
break;
}
case 'date':
case 'time':
if (f.min && text < f.min) return fill(m.minDate, { min: f.min });
if (f.max && text > f.max) return fill(m.maxDate, { max: f.max });
break;
}
const length = [...text].length;
if (f.minLength && length < f.minLength) return fill(m.minLength, { min: f.minLength });
if (f.maxLength && length > f.maxLength) return fill(m.maxLength, { max: f.maxLength });
if (f.pattern) {
let re = null;
try {
re = new RegExp('^(?:' + f.pattern + ')$', 'u');
} catch {
re = null; // a broken pattern is ignored
}
if (re && !re.test(text)) return f.patternMessage || m.pattern;
}
return null;
}
function accepts(file, accept) {
const name = (file.originalname || '').toLowerCase();
const type = (file.mimetype || '').toLowerCase();
return accept
.split(',')
.map((a) => a.trim().toLowerCase())
.filter(Boolean)
.some((rule) => (rule.startsWith('.') ? name.endsWith(rule) : rule.endsWith('/*') ? type.startsWith(rule.slice(0, -1)) : type === rule));
}
function ruleMatches(rule, value) {
const expected = rule.value ?? '';
const list = Array.isArray(value) ? value.map((v) => (v && typeof v === 'object' ? v.originalname : String(v))) : null;
const text = value === undefined || value === null ? '' : list ? list.join(',') : String(value);
const checked = value === true || (list !== null && list.length > 0);
switch (rule.op) {
case 'eq': return list ? list.includes(expected) : text === expected;
case 'neq': return list ? !list.includes(expected) : text !== expected;
case 'contains': return list ? list.includes(expected) : text.toLowerCase().includes(expected.toLowerCase());
case 'notContains': return list ? !list.includes(expected) : !text.toLowerCase().includes(expected.toLowerCase());
case 'empty': return isEmpty(value);
case 'notEmpty': return !isEmpty(value);
case 'gt': return text !== '' && Number(text) > Number(expected);
case 'lt': return text !== '' && Number(text) < Number(expected);
case 'checked': return checked;
case 'unchecked': return !checked;
default: return true;
}
}
function shown(f, seen) {
const rules = (f.showIf && f.showIf.rules) || [];
if (!rules.length) return true;
const results = rules.map((rule) => ruleMatches(rule, seen[rule.field]));
return f.showIf.logic === 'any' ? results.some(Boolean) : results.every(Boolean);
}
/** The names of the fields shown for these answers (conditions can depend on each other). */
function visibleFields(values) {
let visible = new Set(FIELDS.map((f) => f.name));
for (let pass = 0; pass < 5; pass++) {
const seen = Object.fromEntries(Object.entries(values).filter(([name]) => visible.has(name)));
const next = new Set(FIELDS.filter((f) => shown(f, seen)).map((f) => f.name));
if (next.size === visible.size && [...next].every((name) => visible.has(name))) break;
visible = next;
}
return visible;
}
function validate(values, visible) {
const errors = {};
for (const f of FIELDS) {
if (!visible.has(f.name)) continue;
const error = check(f, values[f.name]);
if (error) errors[f.name] = error;
}
return errors;
}
function labelOf(name) {
const f = FIELDS.find((field) => field.name === name);
return f ? f.label : name;
}
function summary(values) {
return Object.entries(values)
.map(([name, value]) => {
const text = typeof value === 'boolean' ? (value ? 'yes' : 'no') : Array.isArray(value) ? value.map((v) => (v && typeof v === 'object' ? v.originalname : v)).join(', ') : String(value);
return labelOf(name) + ': ' + text;
})
.join('\n');
}
function escapeHtml(text) {
return String(text).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
}
function page(body, req) {
const back = req.get('referer') ? '<p><a href="' + escapeHtml(req.get('referer')) + '">' + escapeHtml(MESSAGES.back) + '</a></p>' : '';
return '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Form</title></head>' +
'<body style="font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px">' + body + back + '</body></html>';
}
A minimal API for .NET 8 or later: start with dotnet new web and use this Program.cs, or copy the MapPost call and the WdsForm class into your app.
// Form handler for "Contact us", made with WDS Forms (https://webdevsnippets.com/wds-forms).
// It checks every answer again on the server (never trust the browser alone), then replies with JSON for the
// WDS Forms script, or with a small page for forms sent without JavaScript.
// .NET 8 or later: "dotnet new web", replace Program.cs with this file, then "dotnet run".
// In an existing app, copy the MapPost(...) call and the WdsForm class.
using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapPost("/contact", async (HttpRequest request) =>
{
var values = await WdsForm.ReadValues(request);
var visible = WdsForm.VisibleFields(values);
values = values.Where(v => visible.Contains(v.Key)).ToDictionary(v => v.Key, v => v.Value); // hidden fields are left out
var errors = WdsForm.Validate(values, visible);
var wantsJson = request.Headers.Accept.ToString().Contains("application/json");
if (errors.Count > 0)
{
if (wantsJson) return Results.Json(new { errors }, statusCode: 422);
var items = string.Concat(errors.Select(e => "<li>" + WebUtility.HtmlEncode(WdsForm.Label(e.Key) + ": " + e.Value) + "</li>"));
return Results.Content(WdsForm.Page("<p>" + WebUtility.HtmlEncode(WdsForm.Messages["fix"]) + "</p><ul>" + items + "</ul>", request), "text/html; charset=utf-8", statusCode: 422);
}
// ---------- The answers are valid: save them or email them here. ----------
// values holds the answers by field name; WdsForm.Summary(values) gives them as "Label: answer" lines,
// for example for an email with System.Net.Mail.SmtpClient or MailKit.
// Uploaded files: values["attachment"] is a List<IFormFile>. Save one with:
// await using (var stream = File.Create(Path.Combine("uploads", Path.GetRandomFileName() + Path.GetExtension(file.FileName)))) await file.CopyToAsync(stream);
if (wantsJson) return Results.Json(new { ok = true });
return Results.Content(WdsForm.Page("<p>" + WebUtility.HtmlEncode(WdsForm.Messages["success"]) + "</p>", request), "text/html; charset=utf-8");
});
app.Run();
// ---------- WDS Forms helpers ----------
record WdsRule(string Field, string Op, string? Value);
record WdsCondition(string? Logic, List<WdsRule> Rules);
record WdsField(string Name, string Type, string Label, bool Required, string? Min, string? Max, int? MinLength, int? MaxLength,
string? Pattern, string? PatternMessage, List<string>? Options, bool Multiple, string? Accept, double? MaxSize, WdsCondition? ShowIf);
static class WdsForm
{
static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
public static readonly List<WdsField> Fields = JsonSerializer.Deserialize<List<WdsField>>("""
[
{
"name": "name",
"type": "text",
"label": "Name",
"required": true
},
{
"name": "email",
"type": "email",
"label": "Email",
"required": true
},
{
"name": "topic",
"type": "select",
"label": "Topic",
"required": true,
"options": [
"sales",
"support",
"other"
]
},
{
"name": "order",
"type": "text",
"label": "Order number",
"required": true,
"pattern": "WDS-\\d{5}",
"patternMessage": "Use the format WDS-12345.",
"showIf": {
"logic": "all",
"rules": [
{
"field": "topic",
"op": "eq",
"value": "support"
}
]
}
},
{
"name": "message",
"type": "textarea",
"label": "Message",
"required": true,
"minLength": 10,
"maxLength": 2000
},
{
"name": "attachment",
"type": "file",
"label": "Attachment",
"accept": ".pdf,.jpg,.png",
"maxSize": 5
},
{
"name": "privacy",
"type": "checkbox",
"label": "I agree that my message is stored to answer it",
"required": true
}
]
""", Json)!;
public static readonly Dictionary<string, string> Messages = JsonSerializer.Deserialize<Dictionary<string, string>>("""
{
"required": "This field is required.",
"requiredCheck": "Please check this box.",
"requiredChoice": "Please choose an option.",
"requiredFile": "Please choose a file.",
"email": "Enter a valid email address.",
"url": "Enter a valid web address, starting with http:// or https://.",
"tel": "Enter a valid phone number.",
"number": "Enter a number.",
"min": "Enter {min} or more.",
"max": "Enter {max} or less.",
"minDate": "Choose {min} or later.",
"maxDate": "Choose {max} or earlier.",
"minLength": "Enter at least {min} characters.",
"maxLength": "Enter at most {max} characters.",
"pattern": "The value is not in the expected format.",
"fileSize": "Each file must be {max} MB or smaller.",
"fileType": "This file type is not allowed.",
"success": "Thank you! We will answer within one working day.",
"fix": "Please correct these fields:",
"back": "Go back to the form"
}
""", Json)!;
public static async Task<Dictionary<string, object?>> ReadValues(HttpRequest request)
{
var values = new Dictionary<string, object?>();
if (request.HasJsonContentType())
{
var body = await JsonSerializer.DeserializeAsync<JsonObject>(request.Body) ?? new JsonObject();
foreach (var f in Fields)
{
var node = body[f.Name];
if (f.Type is "checkbox" or "switch")
values[f.Name] = node is JsonValue b && (b.TryGetValue<bool>(out var on) ? on : b.ToString() is "true" or "1" or "on");
else if (node is JsonArray a)
values[f.Name] = a.Select(x => x?.ToString() ?? "").Where(x => x != "").ToList();
else if (node is JsonValue v && !v.TryGetValue<bool>(out _))
values[f.Name] = v.ToString().Trim();
else
values[f.Name] = f.Multiple ? new List<string>() : "";
}
return values;
}
var form = request.HasFormContentType ? await request.ReadFormAsync() : null;
foreach (var f in Fields)
{
var raw = (form != null ? form[f.Name].Concat(form[f.Name + "[]"]) : request.Query[f.Name].Concat(request.Query[f.Name + "[]"])).OfType<string>().ToList();
values[f.Name] = f.Type switch
{
"checkbox" or "switch" => (object?)raw.Any(r => r is "true" or "1" or "on"),
"file" => (object?)(form?.Files.Where(x => (x.Name == f.Name || x.Name == f.Name + "[]") && x.FileName != "").ToList() ?? new List<IFormFile>()),
_ when f.Multiple => raw.Where(r => r != "").ToList(),
_ => (raw.FirstOrDefault() ?? "").Trim()
};
}
return values;
}
static bool IsEmpty(object? value) => value switch
{
null => true,
string s => s == "",
bool b => !b,
System.Collections.ICollection c => c.Count == 0,
_ => false
};
static string Fill(string message, string key, object value) => message.Replace("{" + key + "}", Convert.ToString(value, CultureInfo.InvariantCulture));
static bool Number(string text, out double n) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out n);
static string? Check(WdsField f, object? value)
{
var m = Messages;
if (f.Type == "hidden") return null;
if (IsEmpty(value))
{
if (!f.Required) return null;
return f.Type switch
{
"checkbox" or "switch" => m["requiredCheck"],
"radio" or "checkboxes" or "select" => m["requiredChoice"],
"file" => m["requiredFile"],
_ => m["required"]
};
}
if (value is List<IFormFile> files)
{
foreach (var file in files)
{
if (f.MaxSize is double max && file.Length > max * 1024 * 1024) return Fill(m["fileSize"], "max", max);
if (!string.IsNullOrEmpty(f.Accept) && !Accepts(file, f.Accept)) return m["fileType"];
}
return null;
}
if (f.Options != null) // a choice must be one of the options
{
var chosen = value as List<string> ?? new List<string> { value?.ToString() ?? "" };
return chosen.All(f.Options.Contains) ? null : m["requiredChoice"];
}
if (value is not string text) return null;
switch (f.Type)
{
case "email":
if (!Regex.IsMatch(text, @"^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$")) return m["email"];
break;
case "url":
if (!Uri.TryCreate(text, UriKind.Absolute, out var uri) || (uri.Scheme != "http" && uri.Scheme != "https")) return m["url"];
break;
case "tel":
if (!Regex.IsMatch(text, @"^\+?[0-9\s().-]{5,20}$")) return m["tel"];
break;
case "number":
case "range":
if (!Number(text, out var n)) return m["number"];
if (f.Min != null && Number(f.Min, out var min) && n < min) return Fill(m["min"], "min", f.Min);
if (f.Max != null && Number(f.Max, out var max) && n > max) return Fill(m["max"], "max", f.Max);
break;
case "date":
case "time":
if (!string.IsNullOrEmpty(f.Min) && string.CompareOrdinal(text, f.Min) < 0) return Fill(m["minDate"], "min", f.Min);
if (!string.IsNullOrEmpty(f.Max) && string.CompareOrdinal(text, f.Max) > 0) return Fill(m["maxDate"], "max", f.Max);
break;
}
var length = text.EnumerateRunes().Count();
if (f.MinLength is int minLength && minLength > 0 && length < minLength) return Fill(m["minLength"], "min", minLength);
if (f.MaxLength is int maxLength && maxLength > 0 && length > maxLength) return Fill(m["maxLength"], "max", maxLength);
if (!string.IsNullOrEmpty(f.Pattern))
{
try
{
if (!Regex.IsMatch(text, "^(?:" + f.Pattern + ")$", RegexOptions.None, TimeSpan.FromSeconds(1))) return f.PatternMessage ?? m["pattern"];
}
catch (ArgumentException)
{
// a broken pattern is ignored
}
}
return null;
}
static bool Accepts(IFormFile file, string accept)
{
var name = file.FileName.ToLowerInvariant();
var type = (file.ContentType ?? "").ToLowerInvariant();
return accept.Split(',').Select(a => a.Trim().ToLowerInvariant()).Where(a => a != "").Any(rule =>
rule.StartsWith('.') ? name.EndsWith(rule) : rule.EndsWith("/*") ? type.StartsWith(rule[..^1]) : type == rule);
}
static bool RuleMatches(WdsRule rule, object? value)
{
var expected = rule.Value ?? "";
var list = value switch
{
List<string> l => l,
List<IFormFile> fl => fl.Select(x => x.FileName).ToList(),
_ => null
};
var text = value switch
{
null => "",
bool b => b ? "true" : "false",
_ when list != null => string.Join(",", list),
_ => value.ToString() ?? ""
};
var isChecked = value is true || list is { Count: > 0 };
switch (rule.Op)
{
case "eq": return list != null ? list.Contains(expected) : text == expected;
case "neq": return list != null ? !list.Contains(expected) : text != expected;
case "contains": return list != null ? list.Contains(expected) : text.Contains(expected, StringComparison.OrdinalIgnoreCase);
case "notContains": return list != null ? !list.Contains(expected) : !text.Contains(expected, StringComparison.OrdinalIgnoreCase);
case "empty": return IsEmpty(value);
case "notEmpty": return !IsEmpty(value);
case "gt": return Number(text, out var a) && Number(expected, out var b1) && a > b1;
case "lt": return Number(text, out var c) && Number(expected, out var d) && c < d;
case "checked": return isChecked;
case "unchecked": return !isChecked;
default: return true;
}
}
static bool Shown(WdsField f, Dictionary<string, object?> seen)
{
var rules = f.ShowIf?.Rules ?? new List<WdsRule>();
if (rules.Count == 0) return true;
var results = rules.Select(r => RuleMatches(r, seen.GetValueOrDefault(r.Field))).ToList();
return f.ShowIf?.Logic == "any" ? results.Any(x => x) : results.All(x => x);
}
/// <summary>The names of the fields shown for these answers (conditions can depend on each other).</summary>
public static HashSet<string> VisibleFields(Dictionary<string, object?> values)
{
var visible = Fields.Select(f => f.Name).ToHashSet();
for (var pass = 0; pass < 5; pass++)
{
var seen = values.Where(v => visible.Contains(v.Key)).ToDictionary(v => v.Key, v => v.Value);
var next = Fields.Where(f => Shown(f, seen)).Select(f => f.Name).ToHashSet();
if (next.SetEquals(visible)) break;
visible = next;
}
return visible;
}
public static Dictionary<string, string> Validate(Dictionary<string, object?> values, HashSet<string> visible)
{
var errors = new Dictionary<string, string>();
foreach (var f in Fields)
{
if (!visible.Contains(f.Name)) continue;
var error = Check(f, values.GetValueOrDefault(f.Name));
if (error != null) errors[f.Name] = error;
}
return errors;
}
public static string Label(string name) => Fields.FirstOrDefault(f => f.Name == name)?.Label ?? name;
public static string Summary(Dictionary<string, object?> values) => string.Join("\n", values.Select(v => Label(v.Key) + ": " + v.Value switch
{
bool b => b ? "yes" : "no",
List<string> l => string.Join(", ", l),
List<IFormFile> fl => string.Join(", ", fl.Select(x => x.FileName)),
var other => other?.ToString() ?? ""
}));
public static string Page(string body, HttpRequest request)
{
var referer = request.Headers.Referer.ToString();
var back = referer != "" ? "<p><a href=\"" + WebUtility.HtmlEncode(referer) + "\">" + WebUtility.HtmlEncode(Messages["back"]) + "</a></p>" : "";
return "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Form</title></head>" +
"<body style=\"font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px\">" + body + back + "</body></html>";
}
}
Flask 3 (pip install flask). The same code works as a blueprint; Django and FastAPI only change the routing.
# Form handler for "Contact us", made with WDS Forms (https://webdevsnippets.com/wds-forms).
# It checks every answer again on the server (never trust the browser alone), then replies with JSON for the
# WDS Forms script, or with a small page for forms sent without JavaScript.
# Python 3.9 or later: pip install flask then: python form_handler.py
import html
import re
from urllib.parse import urlparse
from flask import Flask, jsonify, request
FIELDS = [
{"name": "name", "type": "text", "label": "Name", "required": True},
{"name": "email", "type": "email", "label": "Email", "required": True},
{"name": "topic", "type": "select", "label": "Topic", "required": True, "options": ["sales", "support", "other"]},
{"name": "order", "type": "text", "label": "Order number", "required": True, "pattern": "WDS-\\d{5}", "patternMessage": "Use the format WDS-12345.", "showIf": {"logic": "all", "rules": [{"field": "topic", "op": "eq", "value": "support"}]}},
{"name": "message", "type": "textarea", "label": "Message", "required": True, "minLength": 10, "maxLength": 2000},
{"name": "attachment", "type": "file", "label": "Attachment", "accept": ".pdf,.jpg,.png", "maxSize": 5},
{"name": "privacy", "type": "checkbox", "label": "I agree that my message is stored to answer it", "required": True}
]
MESSAGES = {
"required": "This field is required.",
"requiredCheck": "Please check this box.",
"requiredChoice": "Please choose an option.",
"requiredFile": "Please choose a file.",
"email": "Enter a valid email address.",
"url": "Enter a valid web address, starting with http:// or https://.",
"tel": "Enter a valid phone number.",
"number": "Enter a number.",
"min": "Enter {min} or more.",
"max": "Enter {max} or less.",
"minDate": "Choose {min} or later.",
"maxDate": "Choose {max} or earlier.",
"minLength": "Enter at least {min} characters.",
"maxLength": "Enter at most {max} characters.",
"pattern": "The value is not in the expected format.",
"fileSize": "Each file must be {max} MB or smaller.",
"fileType": "This file type is not allowed.",
"success": "Thank you! We will answer within one working day.",
"fix": "Please correct these fields:",
"back": "Go back to the form"
}
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 25 * 1024 * 1024
@app.route("/contact", methods=["POST"])
def form_handler():
values = read_values()
visible = visible_fields(values)
values = {name: value for name, value in values.items() if name in visible} # hidden fields are left out
errors = validate(values, visible)
wants_json = "application/json" in request.headers.get("Accept", "")
if errors:
if wants_json:
return jsonify(errors=errors), 422
items = "".join("<li>" + html.escape(label_of(name) + ": " + error) + "</li>" for name, error in errors.items())
return page("<p>" + html.escape(MESSAGES["fix"]) + "</p><ul>" + items + "</ul>"), 422
# ---------- The answers are valid: save them or email them here. ----------
# values holds the answers by field name; summary(values) gives them as "Label: answer" lines,
# for example for an email with smtplib.
# Uploaded files: values["attachment"] is a list of Flask FileStorage objects. Save one with:
# file.save(os.path.join("uploads", secrets.token_hex(8) + "-" + werkzeug.utils.secure_filename(file.filename)))
if wants_json:
return jsonify(ok=True)
return page("<p>" + html.escape(MESSAGES["success"]) + "</p>")
# ---------- WDS Forms helpers ----------
def read_values():
data = request.get_json(silent=True) if request.is_json else None
values = {}
for f in FIELDS:
name = f["name"]
if data is not None:
raw = data.get(name) if isinstance(data, dict) else None
if f["type"] in ("checkbox", "switch"):
values[name] = raw is True or raw in ("true", "1", "on")
elif isinstance(raw, list):
values[name] = [str(v) for v in raw if v not in (None, "")]
elif raw is None or isinstance(raw, (dict, bool)):
values[name] = [] if f.get("multiple") else ""
else:
values[name] = str(raw).strip()
continue
source = request.form if request.method == "POST" else request.args
raw = source.getlist(name) + source.getlist(name + "[]")
if f["type"] == "file":
values[name] = [x for x in request.files.getlist(name) + request.files.getlist(name + "[]") if x.filename]
elif f["type"] in ("checkbox", "switch"):
values[name] = any(v in ("true", "1", "on") for v in raw)
elif f.get("multiple"):
values[name] = [v for v in raw if v != ""]
else:
values[name] = raw[0].strip() if raw else ""
return values
def is_empty(value):
return value is None or value == "" or value is False or value == []
def fill(message, **values):
for key, value in values.items():
message = message.replace("{" + key + "}", str(value))
return message
def number(text):
try:
return float(text)
except (TypeError, ValueError):
return None
def file_size(file):
file.stream.seek(0, 2)
size = file.stream.tell()
file.stream.seek(0)
return size
def check(f, value):
m = MESSAGES
kind = f["type"]
if kind == "hidden":
return None
if is_empty(value):
if not f.get("required"):
return None
if kind in ("checkbox", "switch"):
return m["requiredCheck"]
if kind in ("radio", "checkboxes", "select"):
return m["requiredChoice"]
if kind == "file":
return m["requiredFile"]
return m["required"]
if kind == "file":
for file in value:
if isinstance(file, str):
continue
if f.get("maxSize") and file_size(file) > f["maxSize"] * 1024 * 1024:
return fill(m["fileSize"], max=f["maxSize"])
if f.get("accept") and not accepts(file, f["accept"]):
return m["fileType"]
return None
if "options" in f: # a choice must be one of the options
chosen = value if isinstance(value, list) else [value]
return None if all(str(c) in f["options"] for c in chosen) else m["requiredChoice"]
if isinstance(value, (bool, list)):
return None
text = str(value)
if kind == "email" and not re.match(r"^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$", text):
return m["email"]
if kind == "url":
parts = urlparse(text)
if parts.scheme not in ("http", "https") or not parts.netloc:
return m["url"]
if kind == "tel" and not re.match(r"^\+?[0-9\s().-]{5,20}$", text):
return m["tel"]
if kind in ("number", "range"):
n = number(text)
if n is None:
return m["number"]
if "min" in f and number(f["min"]) is not None and n < number(f["min"]):
return fill(m["min"], min=f["min"])
if "max" in f and number(f["max"]) is not None and n > number(f["max"]):
return fill(m["max"], max=f["max"])
if kind in ("date", "time"):
if f.get("min") and text < f["min"]:
return fill(m["minDate"], min=f["min"])
if f.get("max") and text > f["max"]:
return fill(m["maxDate"], max=f["max"])
if f.get("minLength") and len(text) < f["minLength"]:
return fill(m["minLength"], min=f["minLength"])
if f.get("maxLength") and len(text) > f["maxLength"]:
return fill(m["maxLength"], max=f["maxLength"])
if f.get("pattern"):
try:
if not re.fullmatch("(?:" + f["pattern"] + ")", text):
return f.get("patternMessage") or m["pattern"]
except re.error:
pass # a broken pattern is ignored
return None
def accepts(file, accept):
name = (file.filename or "").lower()
kind = (file.mimetype or "").lower()
for rule in (a.strip().lower() for a in accept.split(",")):
if not rule:
continue
if rule.startswith("."):
if name.endswith(rule):
return True
elif rule.endswith("/*"):
if kind.startswith(rule[:-1]):
return True
elif kind == rule:
return True
return False
def rule_matches(rule, value):
expected = rule.get("value", "")
items = [v if isinstance(v, str) else v.filename for v in value] if isinstance(value, list) else None
if value is None:
text = ""
elif items is not None:
text = ",".join(items)
elif isinstance(value, bool):
text = "true" if value else "false"
else:
text = str(value)
checked = value is True or bool(items)
op = rule["op"]
if op == "eq":
return expected in items if items is not None else text == expected
if op == "neq":
return expected not in items if items is not None else text != expected
if op == "contains":
return expected in items if items is not None else expected.lower() in text.lower()
if op == "notContains":
return expected not in items if items is not None else expected.lower() not in text.lower()
if op == "empty":
return is_empty(value)
if op == "notEmpty":
return not is_empty(value)
if op in ("gt", "lt"):
a, b = number(text), number(expected)
if a is None or b is None:
return False
return a > b if op == "gt" else a < b
if op == "checked":
return checked
if op == "unchecked":
return not checked
return True
def shown(f, seen):
rules = (f.get("showIf") or {}).get("rules") or []
if not rules:
return True
results = [rule_matches(rule, seen.get(rule["field"])) for rule in rules]
return any(results) if f["showIf"].get("logic") == "any" else all(results)
def visible_fields(values):
"""The names of the fields shown for these answers (conditions can depend on each other)."""
visible = {f["name"] for f in FIELDS}
for _ in range(5):
seen = {name: value for name, value in values.items() if name in visible}
following = {f["name"] for f in FIELDS if shown(f, seen)}
if following == visible:
break
visible = following
return visible
def validate(values, visible):
errors = {}
for f in FIELDS:
if f["name"] not in visible:
continue
error = check(f, values.get(f["name"]))
if error:
errors[f["name"]] = error
return errors
def label_of(name):
return next((f["label"] for f in FIELDS if f["name"] == name), name)
def summary(values):
lines = []
for name, value in values.items():
if isinstance(value, bool):
text = "yes" if value else "no"
elif isinstance(value, list):
text = ", ".join(v if isinstance(v, str) else v.filename for v in value)
else:
text = str(value)
lines.append(label_of(name) + ": " + text)
return "\n".join(lines)
def page(body):
referer = request.headers.get("Referer")
back = '<p><a href="' + html.escape(referer) + '">' + html.escape(MESSAGES["back"]) + "</a></p>" if referer else ""
return (
'<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width, initial-scale=1"><title>Form</title></head>'
'<body style="font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px">'
+ body + back + "</body></html>"
)
if __name__ == "__main__":
app.run(port=5000)
Before you go live, add your own protection where your site needs it: a login check, an anti-forgery token, a rate limit or a CAPTCHA against spam.
HTML without JavaScript
Get code, HTML only gives the form as markup for the selected theme; tick Whole HTML page for a page with the framework's CSS linked. The browser checks required, min, max and pattern itself, and the form is sent as a normal post to its address. Conditional fields and steps need the embed code: in plain HTML all fields are shown and page breaks become headings.
Themes
Pick the theme in the builder's menu; the preview and all the code follow it.
| Theme | Needs on the page |
|---|---|
| Bootstrap 5 | Bootstrap 5 CSS (form-control, form-select, form-check, row g-3) |
| Bootstrap 6 | Bootstrap 6 CSS (form-field, check, radio, switch, md:col-6) |
| Tailwind CSS | Tailwind CSS v4: the browser build, or your own build with the package as a source (below) |
| Plain | The small wds-forms.min.css stylesheet, linked in the embed code |
A Tailwind build only makes the classes it finds in your files. Install wds-forms from npm and add it as a source:
/* app.css (Tailwind CSS v4) */
@import "tailwindcss";
@source "../node_modules/wds-forms/dist";
Field types
| Type | Field | Sent as |
|---|---|---|
| Text, Email, Phone, Password, Website | Single-line inputs with format checks | Text |
| Number, Slider | Number input and slider with its value shown, with lowest and highest | Number |
| Text area | Multi-line text with a length limit | Text |
| Dropdown | Single or multiple choice | Text or list |
| Radio buttons, Checkboxes | One or several options, stacked or side by side | Text or list |
| Checkbox, Switch | A single yes/no, for example accepting the privacy policy | true or nothing |
| Date, Time | The browser's pickers, with earliest and latest | ISO text |
| File upload | Allowed types, size limit, one or more files | Files |
| Hidden | A fixed value such as the page or campaign | Text |
| Heading, Paragraph, Divider | Text and lines between fields | – |
| Page break | Starts a new step | – |
Conditional fields
Any field, heading or paragraph can be shown only when other answers match. Select it in the builder and turn on Show this field only when… in the Logic settings. The rules: is, is not, contains, does not contain, is empty, is not empty, greater than, less than, is checked and is not checked, combined with all or any. For checkboxes and multiple dropdowns, is means "one of the chosen options is". Hidden fields are not checked and not sent, and the server code skips them too.
Multi-step forms
Drag a Page break into the form and everything after it becomes the next step; its label is the step title. The form shows a progress bar, Step 1 of 3 and Back and Next buttons, checks each step before moving on and skips steps whose fields are all hidden.
Validation
Fields are checked when they lose focus after a change, before Next and before sending. Messages appear under the field, the field gets aria-invalid (and is-invalid for Bootstrap) and the focus moves to the first error. The server code checks the same rules again, because a browser check alone can be skipped.
The WDS Forms script
The forms run with WDS Forms, a free and open source script (MIT license, v1.0.0, about 11 KB gzipped, no dependencies). The embed code loads it from jsDelivr; you can also install it from npm or host the file yourself. Load a form JSON you saved from the builder:
<!-- Your page already loads Bootstrap 5 -->
<div id="contact"></div>
<script src="https://cdn.jsdelivr.net/npm/wds-forms@1/dist/wds-forms.min.js"></script>
<script>
fetch('/forms/contact.json')
.then((res) => res.json())
.then((schema) => WDSForms.render('#contact', schema, { theme: 'bootstrap5' }));
</script>
npm install wds-forms
import { render } from 'wds-forms';
import 'wds-forms/style.css'; // only for the plain theme
const form = render('#contact', schema, { theme: 'tailwind' });
form.on('success', ({ values }) => console.log(values));
Listen to the form's events, for example to count a conversion:
// Every form sends events that bubble up the page
document.addEventListener('wdsf:success', (e) => {
console.log('Sent', e.detail.values); // for example: count a conversion or go to a thank-you page
});
// The form object of an embedded form
const form = WDSForms.get(document.querySelector('[data-wds-form]'));
form.setValues({ topic: 'support' });
Send an anti-forgery token, or handle the answers yourself:
WDSForms.render('#contact', schema, {
theme: 'bootstrap5',
// sent with every request to settings.action, for example an anti-forgery token
headers: { 'RequestVerificationToken': token },
// or send the answers yourself
onSubmit: async (values, form) => {
const res = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values)
});
if (res.status === 422) {
form.setErrors((await res.json()).errors);
return false;
}
return res.ok; // false shows the error message
}
});
Show the messages in your language:
WDSForms.render('#contact', schema, {
theme: 'bootstrap5',
messages: {
required: 'Bu alan zorunludur.',
email: 'Geçerli bir e-posta adresi girin.',
minLength: 'En az {min} karakter girin.',
step: 'Adım {n} / {total}',
success: 'Teşekkürler! Formunuz gönderildi.'
}
});
In Node.js the package checks answers with the form JSON itself, the same way as the browser:
// Node.js: check the answers with the form JSON itself
import { validateValues } from 'wds-forms';
import schema from './forms/contact.json' with { type: 'json' };
app.post('/contact', express.json(), (req, res) => {
const errors = validateValues(schema, req.body);
if (Object.keys(errors).length) return res.status(422).json({ errors });
// save or send the message …
res.json({ ok: true });
});
The JSON format
A form is a list of fields plus a few settings. The builder's JSON tab shows it, applies your edits and downloads it, so you can keep your forms and load them again later.
{
"title": "Contact us",
"fields": [
{ "id": "f1", "type": "text", "name": "name", "label": "Name", "required": true, "width": 6 },
{ "id": "f2", "type": "email", "name": "email", "label": "Email", "required": true, "width": 6 },
{
"id": "f3", "type": "select", "name": "topic", "label": "Topic", "placeholder": "Choose…",
"options": [{ "label": "Sales", "value": "sales" }, { "label": "Support", "value": "support" }]
},
{
"id": "f4", "type": "text", "name": "order", "label": "Order number",
"showIf": { "rules": [{ "field": "topic", "op": "eq", "value": "support" }] }
},
{ "id": "f5", "type": "textarea", "name": "message", "label": "Message", "rows": 5, "maxLength": 2000 }
],
"settings": { "action": "/contact", "submitText": "Send", "successMessage": "Thanks, we will reply soon." }
}
Conditions and page breaks in the JSON:
{
"id": "f5", "type": "text", "name": "company", "label": "Company name", "required": true,
"showIf": {
"logic": "any",
"rules": [
{ "field": "customer_type", "op": "eq", "value": "business" },
{ "field": "invoice", "op": "checked" }
]
}
}
{ "id": "p1", "type": "page", "label": "Your details" },
{ "id": "f1", "type": "text", "name": "name", "label": "Name", "required": true },
{ "id": "p2", "type": "page", "label": "Delivery" },
{ "id": "f2", "type": "text", "name": "address", "label": "Address", "required": true }
Field settings: id, type, name (the key the answer is sent under), label, placeholder, help, value (default), required, disabled, readonly, options, multiple, inline, min, max, step, minLength, maxLength, pattern, patternMessage, accept, maxSize (MB), rows, width (3, 4, 6, 8, 9 or 12 of 12), text, level, showIf, className and autocomplete.
Form settings: action, method (post or get), submitAs (form or json), submitText, resetText, nextText, prevText, successMessage, errorMessage, showProgress and buttonAlign (start, center or end).
API
// Forms in the page: <div data-wds-form data-theme="…"><script type="application/json">…</script></div>
WDSForms.renderAll(); // runs by itself when the page has loaded; call it again for forms added later
WDSForms.get(element); // the form object of an embedded form
// A form from JSON
const form = WDSForms.render('#contact', schema, { theme, messages, onSubmit, headers, values, resetOnSuccess });
form.getValues(); // { name: 'Ann', topic: 'sales', … } (hidden conditional fields are left out)
form.setValues({ name: 'Ann' });
form.validate(); // true or false, shows the messages
form.getErrors(); form.setErrors({ email: 'Already registered.' });
form.next(); form.prev(); form.goTo(0); form.step; form.stepCount;
await form.submit(); // true when sent
form.reset();
form.on('change' | 'step' | 'submit' | 'success' | 'error' | 'invalid' | 'reset', (detail) => {});
form.destroy();
// Helpers
WDSForms.toHTML(schema, { theme, standalone }); // static HTML
WDSForms.validate(schema, values); // { email: 'Enter a valid email address.' }, also in Node
WDSForms.version;
Security and Content Security Policy
Labels, options and texts from the JSON are escaped before they are shown. The embed code needs no inline script and no unsafe-eval: allow https://cdn.jsdelivr.net in script-src (and in style-src for the framework CSS from the CDN), or host both files yourself. The form writes no style attributes except the width of the progress bar, which it sets from JavaScript. Always check the answers on the server too; the server code does.
FAQ
Is the form builder free?
Yes. Building forms and copying their code is free, without an account or a limit. The forms and the code you copy are yours: use them on any site, also for clients and in commercial projects.
Do you store my forms or the answers?
No. The builder runs in your browser and nothing you build or type is sent to WebDevSnippets. The answers of your visitors go straight to your own server, to the address you set.
How do I add the form to my website?
Open Get code, copy the Embed code and paste it into your page where the form should appear. Then put the server code for your language at the address the form is sent to. That is all: the form checks the answers, shows conditional fields and steps, and sends without leaving the page.
Which server languages are there?
PHP, Node.js (Express), ASP.NET Core (C#) and Python (Flask). The code is made for your form: it checks every field again with the same rules as the browser, skips fields hidden by their conditions, accepts file uploads and replies the way the form expects. Where it says so, add your own code to save or email the answers.
Can I use the form without JavaScript?
Yes. Get code, HTML only gives static HTML with the browser's own checks (required, min, max, pattern). It is sent as a normal post, and the server code answers it with a simple page. Conditional fields and steps need the embed code.
Which CSS frameworks are supported?
Bootstrap 5, Bootstrap 6 and Tailwind CSS, plus a plain theme with its own small stylesheet for sites without a framework. Switch the theme in the builder and the preview and the code change with it.
Can fields show or hide based on other answers?
Yes. Select a field and turn on "Show this field only when…" in its Logic settings: is, is not, contains, is empty, greater than, is checked and more, combined with all or any. Hidden fields are not checked and not sent, in the browser and in the server code.
Does it make multi-step forms?
Yes. Drag a Page break into the form and it becomes a wizard with a progress bar and Back and Next buttons. Each step is checked before the next one opens.
What runs the form on my site?
WDS Forms, a small open source script (MIT license, about 11 KB gzipped) loaded from the jsDelivr CDN. You can also install it from npm as wds-forms or host the file yourself. It has no dependencies and works with any back end.
Can I translate the messages?
Yes. The labels, help texts and buttons are your own text from the builder, in any language. For the built-in messages such as "This field is required.", render the form with the messages option, and change the same texts in the MESSAGES list of the server code.
Is the form accessible?
Labels are linked to their inputs, groups use fieldset and legend, errors set aria-invalid and are linked with aria-describedby, and the focus moves to the first field with an error. The builder works with the keyboard too.
License
The form builder on this page is free to use. The forms you build and the code you copy from it are yours, for any project, free or paid. The script that runs the forms, WDS Forms, is open source under the MIT license. Need a rich text editor too? Try WDS Editor, free and MIT as well.