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.

JavascriptForm Validation

Code

javascriptsnippet
15 lines
// 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

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.