dataset Reads data-* Validation Rules
Read data-* attributes through camelCase dataset keys and remember every value arrives as a string: numeric validation thresholds need Number coercion first.
Code
// data-* 属性经 dataset 读成驼峰键,且所有值都是字符串
const fields = [...document.querySelectorAll('input[data-validate]')];
for (const field of fields) {
const failed = [];
if (field.dataset.validateRequired === 'true' && field.value.trim() === '') {
failed.push('required');
}
// 阈值来自 data-validate-max:字符串必须先转数字再比较
const max = field.dataset.validateMax ? Number(field.dataset.validateMax) : Infinity;
if (field.value.length > max) {
failed.push('max ' + field.dataset.validateMax);
}
console.log(field.name, failed.length === 0 ? 'validation ok' : 'failed: ' + failed.join(', '));
}What the code does
The cycling part of this snippet is for (const field of fields).
Top-level bindings fields hold the demo state — nothing sits inside a function scope.
Points of care
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Statements that matter
const max = field.dataset.validateMax ? Number(field.dataset.validateMax) : Infinity;
const fields = [...document.querySelectorAll('input[data-validate]')];
failed.push('max ' + field.dataset.validateMax);
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does dataset Reads data-* Validation Rules run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.