2008年9月25日 星期四

身份證字號的validator

下面程式是參考
http://zh.wikipedia.org/wiki/%E4%B8%AD%E8%8F%AF%E6%B0%91%E5%9C%8B%E5%9C%8B%E6%B0%91%E8%BA%AB%E5%88%86%E8%AD%89


這篇文章的身份證字號檢查公式,轉換成Zend framework的validator,進行身份證號碼的驗證。

有了公式之後要進行驗證就比較容易,不用看程式碼去倒推公式,如果沒有公式,光看程式碼,看個老半天,也看不出個所以然來,還要去適應各種程式碼的寫法,太累了,這個公式真是造福大家,直接將公式轉換成Zend Framework的程式碼,就容易多了。

require_once('Zend/Validate/Abstract.php');

class App_Validate_IdCheck extends Zend_Validate_Abstract{
const SIZE='size';
const FORMAT='format';
const CHECK='check';

protected $_messageTemplates=array(
self::SIZE=>"'%value%' 身份證字串長度不符合。",
self::FORMAT=>"'%value%' 的第一個字元必須是英文字母,其他必須是數字。",
self::CHECK=>"'%value%' 是非法的身份證字號。"
);

public function isValid($value){
$this->_setValue($value);
if(strlen($value) !=10){
$this->_error(self::SIZE);
return false;
}

$value=strtoupper($value);
if(!ereg("[A-Z]{1}[0-9]{9}",$value)){
$this->_error(self::FORMAT);
return false;
}

if($this->check($value)){
return true;
}
else{
$this->_error(self::CHECK);
return false;
}
}

private function check($value){
$first=array('A'=>10,'B'=>11,'C'=>12,'D'=>13,'E'=>14,
'F'=>15,'G'=>16,'H'=>17,'I'=>34,'J'=>18,
'K'=>19,'L'=>20,'M'=>21,'N'=>22,'O'=>35,
'P'=>23,'Q'=>24,'R'=>25,'S'=>26,'T'=>27,
'U'=>28,'V'=>29,'W'=>32,'X'=>30,'Y'=>31,
'Z'=>33);
/**
* convert the first alpha character to two digits
* and combines to the rest digits
*/
$value=$first[$value[0]].substr($value,1);

$sum=(int)$value[0];
for($i=1;$i<=9;$i++){
$sum+=$value[$i]*(10-$i);
}

/**
* get the single-digit of 10-$sum
*/
$single=10 - ($sum % 10);

if($single == $value[10]){
return true;
}
else{
return false;
}
}
}

沒有留言: