求助:通过if else语句实现日期输入校验及类名添加的正确方式
Hey there! Let's break down why your validation logic is acting inconsistent—using || works for dates but breaks months, and && does the opposite. The core issue here is likely inverted or incorrect condition logic for your error cases. Let's fix this step by step.
The Root of the Problem
When you use || for dates, you're probably checking for "any invalid scenario" (e.g., date < 1 || date > 31), which works. But if you accidentally used && for months (e.g., month <1 && month>12), that condition will never be true—no number is both less than 1 and greater than 12. Conversely, using && for dates might have accidentally created a condition that only triggers for impossible values, while || for months worked.
Working Solution Code
Let's write explicit validation logic for each input, targeting exactly when an input is invalid, then apply the correct classes:
HTML
<input type="number" id="date-input" placeholder="Enter date (1-31)"> <input type="number" id="month-input" placeholder="Enter month (1-12)">
CSS
.wrong { border: 2px solid #dc2626; /* Red border for errors */ } .correct { border: 2px solid #16a34a; /* Green border for valid inputs */ }
JavaScript
// Grab input elements const dateInput = document.getElementById('date-input'); const monthInput = document.getElementById('month-input'); // Date validation handler function validateDate() { const inputValue = parseInt(this.value, 10); // Check for invalid cases: non-number, <1, or >31 if (isNaN(inputValue) || inputValue < 1 || inputValue > 31) { this.classList.remove('correct'); this.classList.add('wrong'); } else { this.classList.remove('wrong'); this.classList.add('correct'); } } // Month validation handler function validateMonth() { const inputValue = parseInt(this.value, 10); // Check for invalid cases: non-number, <1, or >12 if (isNaN(inputValue) || inputValue < 1 || inputValue > 12) { this.classList.remove('correct'); this.classList.add('wrong'); } else { this.classList.remove('wrong'); this.classList.add('correct'); } } // Bind blur events dateInput.addEventListener('blur', validateDate); monthInput.addEventListener('blur', validateMonth);
Key Fixes Explained
- Explicit Error Conditions: We use
||to check for any invalid scenario (non-number, too low, too high). This makes sense because any one of these makes the input invalid. - Type Conversion:
parseInt()converts the input's string value to a number, so numeric comparisons work correctly. We also checkisNaN()to handle empty or non-numeric inputs. - Class Management: We always remove the opposite class before adding the target one—this prevents both classes from sticking around if the user corrects their input later.
内容的提问来源于stack exchange,提问作者N. Eli

