输入框手机号验证实现咨询:仅支持017开头手机号提交
Hey there! Let's work through this phone number validation feature together—where your submit button only enables when a user enters a phone number starting with 017 (following the full format 017xxxxxxxx). I'll use vanilla JavaScript here so it works across all browsers without needing any frameworks.
Step 1: Build the Basic HTML Structure
First, let's create the input field and submit button. We'll start with the button disabled by default, since we don't want users submitting invalid numbers right off the bat.
<label for="phone">Phone Number:</label> <input type="tel" id="phone" placeholder="017xxxxxxxx" inputmode="numeric"> <button id="submitBtn" disabled>Submit</button>
type="tel"helps mobile users pull up a numeric keypad for easier inputinputmode="numeric"reinforces that only numbers should be entered- The button starts with the
disabledattribute to block early submissions
Step 2: Add the Validation Logic with JavaScript
Next, we'll write code that listens to every change in the input field and checks if the number matches our required format. We'll use a regular expression to test for the 017 prefix followed by exactly 8 more digits (making 11 total characters).
// Grab references to our input and button elements const phoneInput = document.getElementById('phone'); const submitBtn = document.getElementById('submitBtn'); // Listen for any input changes in the phone field phoneInput.addEventListener('input', function() { // Regex rule: must start with 017, followed by exactly 8 numeric digits const validPhoneRegex = /^017\d{8}$/; // Check if the current input matches our regex if (validPhoneRegex.test(this.value)) { // Enable the button if the number is valid submitBtn.removeAttribute('disabled'); } else { // Disable the button if the number is invalid or incomplete submitBtn.setAttribute('disabled', true); } });
Breakdown of How This Works:
- The
inputevent fires every time the user types, deletes, or pastes into the field—so validation happens in real-time - The regex
^017\d{8}$enforces strict formatting:^= ensures the string starts with the following characters017= the mandatory prefix we need\d{8}= requires exactly 8 numeric digits after the prefix$= ensures there are no extra characters at the end
- If the input matches the rule, we remove the
disabledattribute; otherwise, we add it back to lock the button
Optional: Block Non-Numeric Input
To prevent users from typing letters or symbols, you can add this extra listener to the input field:
phoneInput.addEventListener('keypress', function(e) { // Allow only numeric keys and backspace/delete const allowedKeys = ['0','1','2','3','4','5','6','7','8','9','Backspace','Delete']; if (!allowedKeys.includes(e.key)) { e.preventDefault(); } });
That's all! This setup will make sure the submit button is only clickable when a valid 017-prefixed phone number is entered.
内容的提问来源于stack exchange,提问作者Rasel Ahmed Rex

