"Il n'y a pas de problème, il n'y a que des solutions. L'esprit de l'homme invente ensuite le problème." André Gide
LogikDevelopment
Posts Tagged EAN barcode
Validate your EAN barcode
On one of the applications I am working on, I had to validate an EAN (European Article Number) barcode.
This application is mostly using JavaScript validation so I asked my friend Google to find me a JavaScript method which would check my EAN barcode.
It found validators in different languages but none in JavaScript.
Because one is never better served than by oneself, I decided to write it myself and share it with you.
function checkEan(eanCode) {
// Check if only digits
var ValidChars = "0123456789";
for (i = 0; i < eanCode.length; i++) {
digit = eanCode.charAt(i);
if (ValidChars.indexOf(digit) == -1) {
return false;
}
}
// Add five 0 if the code has only 8 digits
if (eanCode.length == 8 ) {
eanCode = "00000" + eanCode;
}
// Check for 13 digits otherwise
else if (eanCode.length != 13) {
return false;
}
// Get the check number
originalCheck = eanCode.substring(eanCode.length - 1);
eanCode = eanCode.substring(0, eanCode.length - 1);
// Add even numbers together
even = Number(eanCode.charAt(1)) +
Number(eanCode.charAt(3)) +
Number(eanCode.charAt(5)) +
Number(eanCode.charAt(7)) +
Number(eanCode.charAt(9)) +
Number(eanCode.charAt(11));
// Multiply this result by 3
even *= 3;
// Add odd numbers together
odd = Number(eanCode.charAt(0)) +
Number(eanCode.charAt(2)) +
Number(eanCode.charAt(4)) +
Number(eanCode.charAt(6)) +
Number(eanCode.charAt(8)) +
Number(eanCode.charAt(10));
// Add two totals together
total = even + odd;
// Calculate the checksum
// Divide total by 10 and store the remainder
checksum = total % 10;
// If result is not 0 then take away 10
if (checksum != 0) {
checksum = 10 - checksum;
}
// Return the result
if (checksum != originalCheck) {
return false;
}
return true;
}
Note that this code can validate EAN-8 and EAN-13 barcodes.
Share this
Tags
a4j:poll Ajax AjaxStateManager ArrayIndexOutOfBoundsException bash Bug BUILD_BEFORE_RESTORE compression COMPRESS_STATE_IN_SESSION cron Facelets Hibernate Hibernate MBean Html Internet Explorer Java JavaScript JExcelAPI JMX Remote JSF JXL Linux locale memory Monitoring MyFaces MySQL No saved view state old browsers onclick Return key RichFaces root context session time out shell SKIP_COMMENTS state manager Tomcat UTF-8 VBScript ViewExpiredException Windows WritableFont Zabbix ZapcatArchives
- August 2010 (2)
- July 2010 (1)
- June 2010 (2)
- May 2010 (3)
- March 2010 (2)
- February 2010 (3)
- January 2010 (2)
- December 2009 (3)
- November 2009 (3)