From 971da213a390d06e61322245ca3f8b01220bd137 Mon Sep 17 00:00:00 2001 From: peterkinamo Date: Fri, 3 Aug 2018 12:28:23 +0200 Subject: [PATCH] Ascii rule added Ascii unit test added --- src/Valitron/Validator.php | 18 ++++++++++++++++++ tests/Valitron/ValidateTest.php | 14 ++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index 313d7e8..eff6d43 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -505,6 +505,24 @@ class Validator return filter_var($value, \FILTER_VALIDATE_EMAIL) !== false; } + /** + * Validate that a field contains only ASCII characters + * + * @param $field + * @param $value + * @return bool|false|string + */ + protected function validateAscii($field, $value) + { + // multibyte extension needed + if (function_exists('mb_detect_encoding')) { + return mb_detect_encoding($value, 'ASCII', true); + } + + // fallback with regex + return 0 === preg_match('/[^\x00-\x7F]/', $value); + } + /** * Validate that a field is a valid e-mail address and the domain name is active * diff --git a/tests/Valitron/ValidateTest.php b/tests/Valitron/ValidateTest.php index 4cf5b59..d77634b 100644 --- a/tests/Valitron/ValidateTest.php +++ b/tests/Valitron/ValidateTest.php @@ -617,6 +617,20 @@ class ValidateTest extends BaseTestCase $this->assertFalse($v->validate()); } + public function testAsciiValid() + { + $v = new Validator(array('text' => '12345 abcde')); + $v->rule('ascii', 'text'); + $this->assertTrue($v->validate()); + } + + public function testAsciiInvalid() + { + $v = new Validator(array('text' => '12345 abcdé')); + $v->rule('ascii', 'text'); + $this->assertFalse($v->validate()); + } + public function testIpValid() { $v = new Validator(array('ip' => '127.0.0.1'));