Step 6
Let's examine the card validation value, CVV. For this demo, it is sufficient to check that CVV is a 3 or 4 digit numeric value.
const cvv = document.getElementById("cvv").value;
if (!/^[0-9]{3,4}$/.test(cvv)) {
window.alert("Invalid CVV. It must be 3 or 4 digits!");
return;
}
Add the above snippet to handleFormSubmit
as shown below:
function handleFormSubmit(event) {
event.preventDefault();
const month = document.getElementById("month").value;
const year = document.getElementById("year").value;
if (new Date() > new Date(year, month)) {
window.alert("Your card is expired!");
return;
}
+ const cvv = document.getElementById("cvv").value;
+ if (!/^[0-9]{3,4}$/.test(cvv)) {
+ window.alert("Invalid CVV. It must be 3 or 4 digits!");
+ return;
+ }
window.alert("Thanks for the payment!");
}
Here is the payment form in action:
To match 3 or 4 digits, I used the following regular expression pattern:
/^[0-9]{3,4}$/
Explanation:
^
: Start of string anchor[0-9]
: Digit between 0 and 9 (you could also use\d
here){3,4}
: A quantifier meaning between 3 and 4 (inclusive).$
: End of string anchor
Regular expressions are patterns used to match character combinations in strings.
Regular expressions are powerful! However, it is beyond the scope of this course to explore them. Instead, please refer to the resources below for more information.
Resources
- A Practical Guide to Regular Expressions (RegEx) In JavaScript.
- RegexOne is a great website with interactive lessons to learn about Regular Expressions.
- Regex Crossword takes a gamification approach to teach you Regular Expressions.
- Try REGEx is a set of interactive tutorials to introduce you to Regular Expressions in JavaScript.
- Scrimba has a great course, Learn Regular Expressions, with 34 interactive screencasts.
- Learn Regular Expressions with this free course on freeCoceCamp is another good place to start.
- Regular Expressions, Chapter 9 of our recommended textbook, Eloquent JavaScript, is another place to learn about Regular Expressions in JavaScrip.
- MDN Web Docs Regular expressions.
- W3 JavaScript Regular Expressions.
- https://regex101.com/ and https://regexr.com/ are great websites that help you build and test regular expressions.