[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
Solved

# UPC validation doesn't work if check digit is 0

Posted on 2006-04-07
Medium Priority
620 Views
Hello,

I have this algorithm which works for all 12-digit UPC codes, unless the final check digit is 0, in which case the validation always comes back as an invalid UPC code. If someone could look through and offer a suggestion or solution I would greatly appreciate it.

function checkUPCFormat12(formObj)
{
var temp = formObj.value.trim();

if (temp.length >11 && temp.length<= 12)
{
var myArray = formObj.value.split('');
step1 = 0;
var tempVar = myArray.length;
for (var i=0;i<tempVar;i=i+2)
{
step1 = step1 + +myArray[i];
}
var step2=step1*3;
step3 = 0;
for(var i=1;i<tempVar-1;i=i+2)
{
step3=step3+(+myArray[i]);
}
step4 = step2 + step3;
step5 = ((Math.floor(step4/10) + 1)*10) - step4;
if (step5 == myArray[myArray.length-1])
{
return true;
}
else
{
alert('You have entered an invalid 12-digit UPC Code. Verify and enter ALL numbers.')
return false;
}
}

Thanks,
R
0
Question by:RickJa

LVL 12

Expert Comment

ID: 16405044
0

LVL 63

Accepted Solution

Zvonko earned 2000 total points
ID: 16405152
From my point of view is check digit zero not allowed.
But if you want it, here my version:

<script>

function checkUPCFormat12(formObj){
//var num = formObj.value.split(""); // this is for form element
var num = formObj.split("");  // this is for String parameter
if(num.length!=12) return false;
var sum = 0;
for(var sum=i=0;i<11;i++){
if(i%2) sum += num[i]*1;
else sum += num[i]*3;
}
if((10-sum%10)%10==num[11]) return true;
return false;
}

</script>

0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
###### Suggested Courses
Course of the Month19 days, 5 hours left to enroll