This JavaScript function checks a text field for a valid credit card number through several validation methods.
// This code validates a credit card number
function ValidateCC(fieldToValidate)
- {
// Validate for numbers only
var ccRE=/\W/gi;
var CCnumber=fieldToValidate.value.replace(ccRE, "");
if(isNaN(CCnumber))
- {
alert("Credit card number is not numeric.");
fieldToValidate.focus();
return false;
- }
// Validate for the number of digits in the credit card number
if((CCnumber.length!=16) && (CCnumber.length!=18))
- {
alert("Incorrect number of digits in credit card number.");
fieldToValidate.focus();
return false;
- }
// More advanced validation using a mathematical formula that applies to all credit card numbers
var cardMath=0;
for (i=CCnumber.length; i>0; i--)
- {
if (i % 2 == 1)
- {
var doubled = "" + (parseInt(CCnumber.substring(i - 1, i)) * 2);
if(doubled.length==2)
- {
doubled = parseInt(doubled.substring(0,1)) + parseInt(doubled.substring(1,2))
- }
cardMath += parseInt(doubled);
- }
- else
{
cardMath += parseInt(CCnumber.substring(i - 1, i))
- }
- }
if(cardMath % 10 != 0)
- {
alert("Credit card number is invalid.");
fieldToValidate.focus();
return false;
- }
- }
/*
<form onSubmit="return ValidateCC(this.txtCC);">
<input type="text" name="txtCC">
<input type="submit" value="Validate">
</form>
*/
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology.
Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach