I'm verifying South African IDs with jQuery, the code below works but Id like to know if it could be simplified in anyway or if there is a better way of doing things here?
South African IDs are verified as follows:
Using ID Number 8001015009087 as an example: Add all the digits in the odd positions (excluding last digit). 8 + 0 + 0 + 5 + 0 + 0 = 13 .............................[1] Move the even positions into a field and multiply the number by 2. 011098 x 2 = 22196 .....................................[2] Add the digits of the result in [2]. 2 + 2 + 1 + 9 + 6 = 20 .................................[3] Add the answer in [3] to the answer in [1]. 13 + 20 = 33 ...........................................[4] Subtract the second digit of [4](i.e. 3) from 10. The number must tally with the last number in the ID Number. If the result is 2 digits, the last digit is used to compare against the last number in the ID Number. If the answer differs, the ID number is invalid.
And the code:
var me = $("#id");
var odd = new Number();
var even_string = new String();
var even_result = new Number();
var even = new Number();
var result = new Number();
// Check length
if( me.val().length == 13 )
{
$.each(me.val(), function(p,v){
if (p%2 == 0 & p != 12)
{
odd += Number(v); // --> 1. Add all odd positions except the last one.
}
else
{
if(p != 12)
{
even_string += String(v); // --> 2.1 Join all even positions.
}
}
});
// 2.2 Multiply even string by two.
even_result = (even_string * 2);
// 3. Add the digits of the new even result in two point two.
$.each(String(even_result), function(p,v){
even += Number(v);
});
// 4. Add answer in three to the answer in one.
result = odd+even;
// 5. Subtract the second digit from step 4. from ten.
result = 10 - Number(String(result).substr(1,1));
// 6. Make sure we use the very last digit on the result.
if( (String(result)).length > 1 )
{
result = Number( (String(result)).charAt( (String(result)).length-1 ) );
}
// 6. The final check
if( Number(result) != me.val().substr(12,1) )
{
// Not a valid South African ID
alert("Your South African ID is not valid.");
}
};
==
and===
. Second, remove all of the==
and!=
you are using that needs no type conversion. \$\endgroup\$document.getElementById
element.value
andfor
. \$\endgroup\$