Version 3.0 will include a few crucial deprecations. This commit adds some soft deprecations to warn users about these changes. Some of the biggest changes are: * The method `validate()` will be renamed to `isValid()`. * The method `validate()` will be repurposed to return an object with failures. * It won't be possible to handle rules directly; users will need to use the `Validator` class to validate with any rule. There will some more changes, but those are some of the most important ones, and are the ones that are easy to deprecate right now.
2.3 KiB
DateTime
DateTime()DateTime(string $format)
Validates whether an input is a date/time or not.
The $format argument should be in accordance to DateTime::format(). See more in the Formats section.
When a $format is not given its default value is Y-m-d H:i:s.
v::dateTime()->isValid('2009-01-01'); // true
Also accepts strtotime() values:
v::dateTime()->isValid('now'); // true
And DateTimeInterface instances:
v::dateTime()->isValid(new DateTime()); // true
v::dateTime()->isValid(new DateTimeImmutable()); // true
You can pass a format when validating strings:
v::dateTime('Y-m-d')->isValid('01-01-2009'); // false
Format has no effect when validating DateTime instances.
Message template for this validator includes {{sample}}.
Formats
Note that this rule validates whether the input matches a given DateTime::format() format and NOT if the input can be parsed with a given DateTimeImmutable::createFromFormat() format. That makes the validation stricter but offers some limitations.
The way DateTimeImmutable::createFromFormat() parses an input allows for many different conversions. Overall DateTimeImmutable::createFromFormat() tend to be more lenient than DateTime::format(). This might be what you desire, and you may want to use Callback to create a custom validation.
$input = '2014-04-12T23:20:50.052Z';
v::callback(fn($input) => is_string($input) && DateTime::createFromFormat(DateTime::RFC3339_EXTENDED, $input))
->isValid($input); // true
v::dateTime(DateTime::RFC3339_EXTENDED)->isValid($input); // false
Categorization
- Date and Time
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Validation became a lot stricter |
| 2.2.4 | v::dateTime('z') is no longer supported. |
| 2.0.0 | Created |
See also: