Browse files

Add TW/IDNumberValidator Test

  • Loading branch information...
1 parent a3d5908 commit 775870744bd22a85e6c528fbe0cc8d4f5951987c @c9s committed Sep 8, 2012
View
26 src/ValidationKit/PhoneNumber/TWPhoneNumberValidator.php
@@ -0,0 +1,26 @@
+<?php
+namespace ValidationKit\PhoneNumber;
+use ValidationKit\Validator;
+
+class TWPhoneNumberValidator extends Validator
+{
+ public function validate($value)
+ {
+ if( preg_match('/^\d{2,3}\d{6,}(?:#\d+)?$/', $value) )
+ return $this->valid();
+ if( preg_match('/^\d{3}$/', $value) )
+ return $this->valid();
+ if( preg_match('/^09\d{8}$/', $value) )
+ return $this->valid();
+
+ if( $this->getOption('allow_dash') ) {
+ if( preg_match('/^09\d{2}-\d{6}$/', $value) )
+ return $this->valid();
+ if( preg_match('/^\d{2,3}-\d{6,}(?:#\d+)?$/', $value) )
+ return $this->valid();
+ }
+ return $this->invalid();
+ }
+}
+
+
View
31 src/ValidationKit/TW/IDNumberValidator.php
@@ -0,0 +1,31 @@
+<?php
+namespace ValidationKit\TW;
+use ValidationKit\Validator;
+
+class IDNumberValidator extends Validator
+{
+
+ public function calculateChecksum($str)
+ {
+ $c = (int) $str[0] * 1;
+ for($i = 1; $i < 11; $i++ ) {
+ $c += $str[$i] * (10-$i);
+ }
+ $mod = $c % 10;
+ return 10 - $mod;
+ }
+
+ public function validate($val) {
+ if( strlen($val) !== 10 )
+ return $this->invalid('length_error');
+ if( ! preg_match('#^[a-zA-Z]\d{9}$#i',$val) )
+ return $this->invalid('format_error');
+
+ $a = stripos('ABCDEFGHJKLMNPQRSTUVWXYZIO',$val[0]) + 10;
+ $c = $this->calculateChecksum($a . substr($val,1));
+ if( $c == substr($val,-1) )
+ return $this->valid();
+ return $this->invalid();
+ }
+}
+
View
28 tests/ValidationKit/PhoneNumber/TWPhoneNumberValidatorTest.php
@@ -0,0 +1,28 @@
+<?php
+
+class TWPhoneNumberValidatorTest extends PHPUnit_Framework_TestCase
+{
+ function testAllowDash()
+ {
+ $validator = new ValidationKit\PhoneNumber\TWPhoneNumberValidator(array( 'allow_dash' => true ));
+ ok($validator);
+ ok($validator->validate('0975123123'));
+ ok($validator->validate('0975-123123'));
+ ok($validator->validate('06-237000344'));
+ not_ok($validator->validate('06-'));
+ ok($validator->validate('110'));
+ }
+
+ function testNonDash()
+ {
+ $validator = new ValidationKit\PhoneNumber\TWPhoneNumberValidator;
+ ok($validator);
+ ok($validator->validate('0975123123'));
+ not_ok($validator->validate('06-237000344'));
+ not_ok($validator->validate('0975-123123'));
+ not_ok($validator->validate('06-'));
+ ok($validator->validate('110'));
+ }
+}
+
+
View
15 tests/ValidationKit/TW/IDNumberValidatorTest.php
@@ -0,0 +1,15 @@
+<?php
+
+class IDNumberValidatorTest extends PHPUnit_Framework_TestCase
+{
+ function test()
+ {
+ $v = new ValidationKit\TW\IDNumberValidator;
+ ok($v);
+ ok($v->validate('A136411883'));
+ ok($v->validate('A178161208'));
+ ok($v->validate('A157354749'));
+ ok($v->validate('I155729562'));
+ }
+}
+

0 comments on commit 7758707

Please sign in to comment.