Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

luhn algorithm javascript

/*
HTML:
<form action="">
      <label for="cardNum">Card Number</label><br>
      <input type="text" id="cardNum" placeholder="Please type your credit card number here..."><br>
</form>
<button onclick="checkIfPassLuhn()" class="checker">Check if the above number passes the Luhn Algorithm</button>
*/

function checkIfPassLuhn() {
    var num = document.getElementById("cardNum").value;
    var array = (num + '').split('').reverse().map(x => parseInt(x));
    var theLastDig = array.shift();
    let sum = array.reduce((prevVal, curVal, index) => (index % 2 !== 0 ? prevVal + curVal : prevVal + ((curVal *= 2) > 9 ? curVal - 9 : curVal)), 0);
    sum += theLastDig;
    if(sum % 10 === 0){
        alert("Your number is correct!");
    }else{
        alert("Your number is incorrect");
    }
}
//Call the method with an HTML element
Comment

luhn algorithm javascript

/**
 * Luhn algorithm in JavaScript: validate credit card number supplied as string of numbers
 * @author ShirtlessKirk. Copyright (c) 2012.
 * @license WTFPL (http://www.wtfpl.net/txt/copying)
 */
var luhnChk = (function (arr) {
    return function (ccNum) {
        var 
            len = ccNum.length,
            bit = 1,
            sum = 0,
            val;

        while (len) {
            val = parseInt(ccNum.charAt(--len), 10);
            sum += (bit ^= 1) ? arr[val] : val;
        }

        return sum && sum % 10 === 0;
    };
}([0, 2, 4, 6, 8, 1, 3, 5, 7, 9]));
Comment

PREVIOUS NEXT
Code Example
Javascript :: js get external script to currnet page 
Javascript :: display array javascript 
Javascript :: sveltekit disable ssr 
Javascript :: loading button jquery 
Javascript :: how to count click events javascript 
Javascript :: javascript detect time on page 
Javascript :: js create jaon object from for loop 
Javascript :: JS copy image 
Javascript :: socket io stream 
Javascript :: mongoose model and joi validation 
Javascript :: add text to innerhtml javascript 
Javascript :: arithmetic expressions in scheme 
Javascript :: does javascript buelt applications 
Javascript :: JavaScript chop/slice/trim off last character in string 
Python :: ipython autoreload 
Python :: how to open a website in python 
Python :: save a dict to pickle 
Python :: max columns in python 
Python :: is pythin a real coding language 
Python :: check if message is in dm discord.py 
Python :: install fastapi conda 
Python :: python get utc time 
Python :: ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True site:stackoverflow.com 
Python :: pylsp install 
Python :: pandas replace null with 0 
Python :: python pygame screen example 
Python :: get common elements from two lists 
Python :: python create directory 
Python :: python rotate screen 
Python :: axis number size matplotlib 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =