开发者

Strip spaces before performing Luhn check

I have a function that performs a Luhn check on a card entry when a form is posted开发者_运维问答.

<script language="javascript">
 function Calculate(Luhn)
{
var sum = 0;
for (i=0; i<Luhn.length; i++ )
{
    sum += parseInt(Luhn.substring(i,i+1));
}
var delta = new Array (0,1,2,3,4,-4,-3,-2,-1,0);
for (i=Luhn.length-1; i>=0; i-=2 )
{       
    var deltaIndex = parseInt(Luhn.substring(i,i+1));
    var deltaValue = delta[deltaIndex]; 
    sum += deltaValue;
}   
var mod10 = sum % 10;
mod10 = 10 - mod10; 
if (mod10==10)
{       
    mod10=0;
}
return mod10;
}

function Validate(Luhn)
{
var LuhnDigit = parseInt(Luhn.substring(Luhn.length-1,Luhn.length));
var LuhnLess = Luhn.substring(0,Luhn.length-1);
if (Calculate(LuhnLess)==parseInt(LuhnDigit))
{
    return true;
}
alert("\n\nYou have mis-typed your card number! \nPlease check and correct.\n\n")   
return false;
}

I also have a function that removes any spaces that may have been entered in the card number onblur.

function stripChar(sValue, sChar) {
var i, tempChar, buildString;
buildString = ""
for (var i=0; i<sValue.length; i++) {
    tempChar = sValue.charAt(i);
    if (tempChar != sChar) {
        buildString = buildString + tempChar;
    }
}
return buildString;

How do I combine the functions so that the spaces are removed and the card number checked onblur.


In your onblur function you could use:

Validate(stripChar(sValue, sChar));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜