+展开-ActionScript
var sum:Number = 0;
for ( var i:Number=0; i < UPC.length; i += 2){
sum += Number(UPC.charAt(i)) * 3;
}
for ( i = 1; i < UPC.length-1; i += 2) {
sum += Number(UPC.charAt(i));
}
var checkSum:Number = ( 10 - (sum % 10) ) % 10;
//如果检验和不对, 就返回一个验证错误
if ( Number(UPC.charAt(11)) != checkSum ) {
results.push(new ValidationResult(true, null, "invalidUPC", "Invalid UPC Number."));
return results;
}
+展开-ActionScript
package com.passalong.utils
{
import mx.validators.Validator;
import mx.validators.ValidationResult;
import mx.controls.Alert;
public class UPCValidator extends Validator
{
private var results:Array;
public function UPCValidator()
{
super();
}
override protected function doValidation(value:Object):Array
{
//把数值转换成字符串, 以方便对个别数字进行分析
var UPC:String = String(value);
// strip off decimal point from beginning -- added to force recognition of leading zeros
UPC = UPC.substring(1);
var UPCnum:Number = Number(UPC);
// 把results这个数组清空
results = [];
//呼叫doValidation()这个基础类
results = super.doValidation(value);
// Return if there are errors.
if (results.length > 0)
return results;
// 如果输入数据不是数目字或不是一个数值, 返回一个验证错误
if (isNaN(UPCnum) || !value )
{
results.push(new ValidationResult(true, null, "NaN", "UPC required."));
return results;
}
if ( UPC.length != 12 )
{
results.push(new ValidationResult(true, null, "invalidUPCLength","Please enter a full 12-digit UPC."));
return results;
}
else
{
var sum:Number = 0;
for ( var i:Number=0; i < UPC.length; i += 2)
sum += Number(UPC.charAt(i)) * 3;
for ( i = 1; i < UPC.length-1; i += 2) {
sum += Number(UPC.charAt(i));
}
var checkSum:Number = ( 10 - (sum % 10) ) % 10;
//如果检验和不正确, 返回一个验证错误
if ( Number(UPC.charAt(11)) != checkSum )
{
results.push(new ValidationResult(true, null, "invalidUPC", "Invalid UPC Number."));
return results;
}
return results;
}
}
}
}