Creating Function
Let's create a function that gets tc id as an argument
var checkTcNum = function(value) { };
Convert id to string to break apart sub elements
value = value.toString();
Check if value contains only digits and it's length is eleven.
var isEleven = /^[0-9]{11}$/.test(value);
For loop to concat first 10 digit of value
and check if it's modulus
equals to 11th position number
var totalX = 0; for (var i = 0; i < 10; i++) { totalX += Number(value.substr(i, 1)); } var isRuleX = totalX % 10 === value.substr(10,1);
Create two variable that holds even and odd positioned numbers summed up.
var totalY1 = 0; var totalY2 = 0;
For loop to sum up even positioned numbers
for (var i = 0; i < 10; i+=2) { totalY1 += Number(value.substr(i, 1)); }
For loop to sum up odd positioned numbers
for (var i = 1; i < 10; i+=2) { totalY2 += Number(value.substr(i, 1)); }
Check if (even positioned numbers summed up multiply with 7) minus (odd positioned numbers summed up) modulus of 10 equals to 10th positioned digit. And, assing it to isRuleY variable.
var isRuleY = ((totalY1 * 7) - totalY2) % 10 == value.substr(9,0); return isEleven && isRuleX && isRuleY;
Complete snippet as Github Gist
Live Demonstration from CodePen
See the Pen Validate TC ID with Javascript by Ömer Aslanbakan (@Aslanbakan) on CodePen.
Published by Ömer Aslanbakan on