logo

cleave.jsで時間を範囲入力

HTML

<input id="input" placeholder="HH:mm 〜 HH:mm" />

Javascript

let result = ''; new Cleave('#input', { blocks: [2, 2, 2, 2], delimiters: [':', ' 〜 ', ':'], numericOnly: true, onValueChanged: function (e) { let { rawValue } = e.target; if (result === rawValue) { return; } result = ''; this.properties.blocks.forEach((len, index) => { if (rawValue.length) { let sub = rawValue.slice(0, len); const sub0 = sub.slice(0, 1); const rest = rawValue.slice(len); switch (index) { case 0: case 2: if (Number(sub0) > 2) { sub = `0${sub0}`; } else if (Number(sub) > 24) { sub = '24'; } break; case 1: case 3: if (Number(sub0) > 5) { sub = `0${sub0}`; } else if (Number(sub) > 60) { sub = '00'; } break; default: break; } result += sub; rawValue = rest; } }); this.setRawValue(result); }, });