From e5815780a14a4873c1990933ad2a168b4183dab5 Mon Sep 17 00:00:00 2001 From: Paulo Tokimatu Date: Mon, 17 Sep 2018 16:21:29 -0500 Subject: [PATCH] Added error message in DateTime constraint. --- src/Constraint/DateTime.php | 5 ++++ tests/Constraint/DateTimeTest.php | 39 +++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 tests/Constraint/DateTimeTest.php diff --git a/src/Constraint/DateTime.php b/src/Constraint/DateTime.php index c1bf6dc..5506aeb 100644 --- a/src/Constraint/DateTime.php +++ b/src/Constraint/DateTime.php @@ -6,6 +6,11 @@ class DateTime extends Constraint { + public function __construct(string $errorMessage = null) + { + $this->setErrorMessage($errorMessage ?? 'Invalid date/time format'); + } + public function validate($content): bool { if (!is_string($content)) { diff --git a/tests/Constraint/DateTimeTest.php b/tests/Constraint/DateTimeTest.php new file mode 100644 index 0000000..3f22966 --- /dev/null +++ b/tests/Constraint/DateTimeTest.php @@ -0,0 +1,39 @@ +assertFalse($constraint->validate('foobar@baz.com')); + $this->assertFalse($constraint->validate('2018-01-99')); + $this->assertFalse($constraint->validate(123)); + } + + public function testIsCheckingValidData() + { + $constraint = new DateTime(); + $this->assertTrue($constraint->validate('2018-01-01')); + $this->assertTrue($constraint->validate('2010-12-31T00:00:00+00:00')); + $this->assertTrue($constraint->validate('2006-12-12 10:00:00.5')); + } + + public function testIsGettingErrorMessage() + { + $constraint = new DateTime(); + $this->assertFalse($constraint->validate('foo/bar')); + $this->assertEquals('[field] Invalid date/time format', $constraint->getErrorMessage('field')); + } + + public function testErrorMessageIsCustomizable() + { + $constraint = new DateTime('CUSTOM!'); + $this->assertSame('[field] CUSTOM!', $constraint->getErrorMessage('field')); + } +}