diff --git a/src/Rule/MatchesRegex.php b/src/Rule/MatchesRegex.php new file mode 100644 index 0000000..cdcd285 --- /dev/null +++ b/src/Rule/MatchesRegex.php @@ -0,0 +1,52 @@ +regex = $regex; + $this->message = $message; + } + + /** + * Validates a value according to this rule and returns if it is valid or not + * @param mixed $v + * @return bool true if valid, otherwise false + */ + public function validate($v): bool + { + return preg_match($this->regex, $v) != 0?true:false; + } + + /** + * Returns the message to be used in case the validation did not pass + * @param mixed $v the value that did not pass the validation + * @return string + */ + public function getMessage($v): string + { + return $this->message?:"'${$v}' does not match provided regex"; + } +} \ No newline at end of file diff --git a/src/Rule/MaxLength.php b/src/Rule/MaxLength.php index 7f6f7c1..f32b908 100644 --- a/src/Rule/MaxLength.php +++ b/src/Rule/MaxLength.php @@ -35,6 +35,6 @@ public function validate($v): bool */ public function getMessage($v): string { - return $this->message ?: "The length of '{$v}' was expected to be at most {$this->length} characters long"; + return $this->message?:"The length of '{$v}' was expected to be at most {$this->length} characters long"; } } diff --git a/tests/Rule/MatchesRegexTest.php b/tests/Rule/MatchesRegexTest.php new file mode 100644 index 0000000..2341932 --- /dev/null +++ b/tests/Rule/MatchesRegexTest.php @@ -0,0 +1,18 @@ +assertTrue($ruleFirst->validate("hello1")); + $this->assertFalse($ruleFirst->validate("hello")); + $this->assertEquals("Custom message",$ruleSecond->getMessage("hello")); + } +} \ No newline at end of file diff --git a/tests/Rule/MaxLengthTest.php b/tests/Rule/MaxLengthTest.php index 1125fc1..27f6da9 100644 --- a/tests/Rule/MaxLengthTest.php +++ b/tests/Rule/MaxLengthTest.php @@ -10,16 +10,16 @@ class MaxLengthTest extends TestCase public function testValidate() { $firstRule = new MaxLength(5); - $secondRule = new MaxLength(5, 'Custom message'); - $this->assertTrue($firstRule->validate('test')); - $this->assertFalse($firstRule->validate('long test')); + $secondRule = new MaxLength(5,"Custom message"); + $this->assertTrue($firstRule->validate("test")); + $this->assertFalse($firstRule->validate("long test")); $this->assertEquals( "The length of 'arr' was expected to be at most 5 characters long", - $firstRule->getMessage('arr') + $firstRule->getMessage("arr") ); $this->assertEquals( - 'Custom message', - $secondRule->getMessage('arr') + "Custom message", + $secondRule->getMessage("arr") ); } -} +} \ No newline at end of file