如何实现仅允许输入6位数字的HTML数字输入框?
Hey there! Let's fix up that input to make sure it only accepts exactly 6 digits, since your current setup has a couple of gotchas (like maxlength not working reliably on type="number" inputs). Here's how to get it working perfectly:
The type="number" input has some quirks—maxlength doesn't behave as expected, and it allows decimals/negative numbers which you don't need for a YYMMDD format. Instead, use type="tel" (it brings up a numeric keyboard on mobile) or type="text", then add these key attributes to enforce strict 6-digit input:
maxlength="6": Directly limits the input lengthpattern="\d{6}": Ensures only digits are entered, exactly 6 of theminputmode="numeric": Hints to browsers to show a numeric keyboard (great for mobile usability)
Updated HTML code:
<input type="tel" placeholder="YYMMDD" id="myKadA" maxlength="6" pattern="\d{6}" inputmode="numeric" style="width:90px !important" onchange="checkMyKad()" oninput="enforceDigitLimit(this)" size="8" class="form-control block-centered ic-input" required >
Your existing CSS handles WebKit browsers, but let's add support for Firefox to ensure no spin buttons show up anywhere:
/* Remove number input spin buttons for WebKit browsers */ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } /* Remove spin buttons for Firefox */ input[type="number"] { -moz-appearance: textfield; } /* Note: If using type="tel" or "text", you won't need this CSS, but keep it handy if you ever switch back to number type */
Even with HTML attributes, adding JS ensures users can't type non-digit characters and keeps the length capped immediately. Here's the helper function and an enhanced version of your checkMyKad:
// Prevent non-digit input and limit to 6 characters in real-time function enforceDigitLimit(input) { // Strip any non-digit characters input.value = input.value.replace(/\D/g, ''); // Trim to max 6 digits if user tries to type more if (input.value.length > 6) { input.value = input.value.slice(0, 6); } } // Enhanced validation function for your YYMMDD input function checkMyKad() { const input = document.getElementById('myKadA'); const isValid = /^\d{6}$/.test(input.value); if (!isValid) { alert('Please enter exactly 6 digits in YYMMDD format'); // Add visual feedback (optional but helpful) input.classList.add('is-invalid'); } else { input.classList.remove('is-invalid'); // Add your post-validation logic here } }
type="tel"balances mobile usability (numeric keyboard) with propermaxlengthsupportpatterntriggers native browser form validation, so users get built-in error prompts if they enter invalid input- The JS function stops non-digits from being typed and caps the length instantly, preventing frustration
- Cross-browser CSS ensures a clean, consistent look across all major browsers
内容的提问来源于stack exchange,提问作者Jacel

