Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNeil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 Pointsinput accepts only numbers
I'm trying to get it so that the input field only accepts numbers. I used a varible called "numbers" and said that if the input field was not equal to any numbers then it should display the error message, yet it doesn't. any tips?
HTML
<div class="col-6 col">
<label for="cc-num" id="ccn_label">Card Number:</label>
<input id="cc-num" name="user_cc-num" type="text">
</div>
JS
const ccn_num = document.getElementById("cc-num");
ccn_num.addEventListener("keyup", (e) => {
let numbers = /^[0-9]+$/;
if(credit_card_number.value.length === 0){
e.preventDefault();
ccn_message.textContent = "Please enter a credit card number in the field below.";
ccn_message.style.color = "#cc0000";
ccn_message.style.display = "block";
ccn_message.className = "warning";
ccn_message.style.fontSize = "1em";
ccn_label.appendChild(ccn_message);
}
else if(credit_card_number.value.length < 13 || credit_card_number.value.length > 16 && !numbers.test(credit_card_number.value) ){
e.preventDefault();
ccn_message.textContent = "Please provide a valid credit card number. Thank you.";
ccn_message.style.color = "#cc0000";
ccn_message.style.display = "block";
ccn_message.className = "warning";
ccn_message.style.fontSize = "1em";
ccn_label.appendChild(ccn_message);
}
else{
ccn_message.style.display = "none";}
})
2 Answers
Steven Parker
231,269 PointsThe non-identity operator ("!==") does not recognize regular expressions.
All it does is tell you if what you are comparing to is not another reference to the same regex object.
To use the regex to check your number, you'll need to apply a method that specifically uses a regex.
Neil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 Pointswere you born a genius? lol Thanks a lot again buddy haha
Neil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 PointsNeil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 PointsI edited the code to this, thought this would work, still doesn't seem to...
&& !numbers.test(credit_card_number.value)
Steven Parker
231,269 PointsSteven Parker
231,269 PointsWhat about that "&&" logic — did you mean to perform that numbers test only if the length is greater than 16? Or should that "&&" be another "||"?