Calculate the last digit verification code of the EAN-13 standard bar code using Javascript

Source: Internet
Author: User

Today, I saw my colleagues in the Group talking about the last verification code of the EAN-13 standard bar code, so I wrote this algorithm with js. Today's Monday is the beginning of a week. I wish you a good mood every day!


/*

The calculation steps of the last digit verification code of the EAN-13 standard Bar Code are as follows:

A. The sum of all the even digit codes starting from code position 2.

B. Multiply the sum of step a by 3.

C. sum the numeric codes of all odd digits starting from code position 3.

D. Add the result of step B and Step c.

E. Use a number greater than or equal to step d and a minimum integer multiple of 10 minus step d. The difference is the value of the obtained verification code. Explanation: EAN-13 standard bar code positions from right to left serial 13 12 11 10 9 8 7 6 5 4 3 2 1

Author: wangfan

Created on:

*/Function isBarCode (s ){

Var reg = new RegExp (/^ [0-9] {12} $ /);

If (reg.exe c (s. substring (0, 12) return true;

Else return false;

}

Function CheckBarCode (s)

{

If (! IsBarCode (s ))

{

Return "An error occurred while verifying the first 12 digits of the barcode! ";

}

Var a = 0;

Var B = 0;

Var c = 0;

Var d = 0;

Var e = 0;

For (var I = 1; I <= 12; I ++)

{

Var SC = parseInt (s [I-1]);

If (I <= 12 & I % 2 = 0)

{

A + = SC;

}

Else if (I <= 11 & I % 2 = 1)

{

B + = SC;

}

}

C = a * 3;

D = B + c;

If (d % 10 = 0)

E = d-d;

Else

E = d + (10-d % 10)-d;

Return e;

}

Alert ("Check Code:" + CheckBarCode ("693721090010X "));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.