Skip to content

Commit 0ec8b2f

Browse files
committed
Add ‘regex’ rule for strings
1 parent 506327e commit 0ec8b2f

File tree

2 files changed

+7
-4
lines changed

2 files changed

+7
-4
lines changed

src/Validator.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -628,10 +628,10 @@ protected function validateString($value, array $rule = []): bool
628628

629629
if (isset($rule['equals']) && is_string($rule['equals'])) {
630630
$valid = $valid && $value == $rule['equals'];
631-
}
632-
633-
if (isset($rule['in']) && is_array($rule['in'])) {
631+
} elseif (isset($rule['in']) && is_array($rule['in'])) {
634632
$valid = $valid && in_array($value, $rule['in']);
633+
} elseif (isset($rule['regex']) && is_string($rule['regex'])) {
634+
$valid = $valid && preg_match($rule['regex'], $value);
635635
}
636636

637637
if (isset($rule['allow_empty']) && $rule['allow_empty'] === false) {
@@ -826,7 +826,7 @@ protected function validateDateTime($value, array $rule = []): bool
826826
$value = (string) $value;
827827
$compare = $value;
828828

829-
if(strlen($compare) == 4){
829+
if (strlen($compare) == 4) {
830830
// Value is presumably a 4-digit year (e.g. 2016) and as-is doesn't
831831
// play nice with strtotime() or date_create()
832832
$compare .= "-01-01";

tests/ValidatorTest.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,7 @@ public function testValidateString()
342342
$str_allow_null = ['allow_null' => true];
343343
$str_equals = ['equals' => 'Hello, World!'];
344344
$str_in = ['in' => ['hello', 'world', 'foo', 'bar']];
345+
$str_regex = ['regex' => "/php/i"];
345346

346347
$this->assertTrue(Validator::isString('abc', array_merge($str_min_length, $str_max_length)));
347348
$this->assertFalse(Validator::isString('', $str_min_length));
@@ -354,6 +355,8 @@ public function testValidateString()
354355
$this->assertFalse(Validator::isString('Hello World!', $str_equals));
355356
$this->assertTrue(Validator::isString('foo', $str_in));
356357
$this->assertFalse(Validator::isString('cat', $str_in));
358+
$this->assertTrue(Validator::isString('PHP is my favorite!', $str_regex));
359+
$this->assertFalse(Validator::isString('Java is my favorite!', $str_regex));
357360
}
358361

359362
/**

0 commit comments

Comments
 (0)