18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Regular Expressions<br />

if (reMasterCard.test(sText)) {<br />

var sCardNum = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;<br />

return luhnCheckSum(sCardNum);<br />

}<br />

} else {<br />

return false;<br />

}<br />

You can now pass in MasterCard numbers like this:<br />

alert(isValidMasterCard(“5432 1234 5678 9012”)); //outputs “false”<br />

alert(isValidMasterCard(“5432-1234-5678-9012”)); //outputs “false”<br />

alert(isValidMasterCard(“5432123456789012”)); //outputs “false”<br />

<strong>For</strong> other types of credit cards, you must know the rules governing their credit card numbers.<br />

Visa card numbers can have either 13 or 16 digits and the first digit must always be 4, therefore, the pattern<br />

to match a Visa number (with no spaces) is:<br />

var reVisa = /^(4\d{12}(?:\d{3})?)$/;<br />

A couple of things to note in this pattern:<br />

❑<br />

❑<br />

A non-capturing group surrounds the final three digits of the card number because these three<br />

digits alone aren’t of much use.<br />

The question mark after the non-capturing group indicates that there should be either three<br />

more digits or no more digits.<br />

With the regular expression complete, you just extract the number and apply the Luhn algorithm:<br />

function isValidVisa(sText) {<br />

var reVisa = /^(4\d{12}(?:\d{3})?)$/;<br />

}<br />

if (reVisa.test(sText)) {<br />

return luhnCheckSum(RegExp.$1);<br />

} else {<br />

return false;<br />

}<br />

<strong>For</strong> more on credit card number patterns and using Luhn’s algorithm, see http://<br />

www.beachnet.com/~hstiles/cardtype.html.<br />

221

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!