Link to home
Start Free TrialLog in
Avatar of RickJa
RickJa

asked on

UPC validation doesn't work if check digit is 0

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])
            {
            //alert('valid UPC Code')
            return true;
            }
            else
            {
            alert('You have entered an invalid 12-digit UPC Code. Verify and enter ALL numbers.')
            return false;
            }
      }

Thanks,
R
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial