使用JavaScript验证数字输入:阻止句号符号通过模式校验
The problem you're facing is a common quirk with <input type="number"> elements: browsers treat these inputs specially, and the pattern attribute doesn't fully control real-time keystroke blocking—decimal points (.) are still allowed because they're considered valid for numeric values, even when your min and max are integers. The pattern attribute here only kicks in during form validation, not while the user is typing.
Here are two reliable solutions to block dots and enforce integer-only input:
Solution 1: Keep type="number" and Add JavaScript Controls
This approach preserves the number input's native UI (like spin buttons) while blocking unwanted characters:
HTML (unchanged)
<input type="number" id="job-priority" min="1" max="99" pattern="[0-9]+" placeholder="1 (High) — 99 (Low)" style="width:186px; padding-left:14px; text-align:center;">
JavaScript
const priorityInput = document.getElementById('job-priority'); // Block forbidden keystrokes in real-time priorityInput.addEventListener('keydown', (e) => { const forbiddenKeys = ['e', 'E', '+', '-', '.']; if (forbiddenKeys.includes(e.key)) { e.preventDefault(); } }); // Sanitize pasted text to remove non-digit characters priorityInput.addEventListener('paste', (e) => { e.preventDefault(); const pastedText = e.clipboardData.getData('text'); const sanitizedText = pastedText.replace(/[^0-9]/g, ''); this.value += sanitizedText; }); // Clean up any remaining invalid characters and enforce min/max priorityInput.addEventListener('input', () => { this.value = this.value.replace(/[^0-9]/g, ''); const value = parseInt(this.value); if (value < 1) this.value = 1; if (value > 99) this.value = 99; });
This code covers all bases: it blocks forbidden keys as they're pressed, sanitizes pasted content, and ensures the final value stays within your 1-99 range.
Solution 2: Switch to type="text" for Full Control
If you don't need the native number input spin buttons, using a text input gives you tighter control over allowed characters:
HTML
<input type="text" id="job-priority" minlength="1" maxlength="2" pattern="[0-9]+" placeholder="1 (High) — 99 (Low)" style="width:186px; padding-left:14px; text-align:center;">
JavaScript
const priorityInput = document.getElementById('job-priority'); // Enforce digits-only input and limit length to 2 characters priorityInput.addEventListener('input', () => { this.value = this.value.replace(/[^0-9]/g, ''); if (this.value.length > 2) this.value = this.value.slice(0, 2); }); // Optional: Add custom spin button functionality if needed const increment = () => { let value = parseInt(priorityInput.value) || 1; if (value < 99) priorityInput.value = value + 1; }; const decrement = () => { let value = parseInt(priorityInput.value) || 1; if (value > 1) priorityInput.value = value - 1; };
You can add - and + buttons next to the input to mimic the number input's spin behavior if desired.
内容的提问来源于stack exchange,提问作者user8293395

