Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions InquirerPy/validator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Module contains pre-built validators."""
import re
from datetime import datetime
from pathlib import Path
from typing import Optional

Expand All @@ -10,6 +11,7 @@
"EmptyInputValidator",
"PasswordValidator",
"NumberValidator",
"DateValidator"
]


Expand Down Expand Up @@ -163,3 +165,41 @@ def validate(self, document) -> None:
raise ValidationError(
message=self._message, cursor_position=document.cursor_position
)


class DateValidator(Validator):
""":class:`~prompt_toolkit.validation.Validator` to validate if input is a valid date.

Args:
message: Error message to display in the validatation toolbar when validation failed.
format: Specify the desired date format.
"""

def __init__(
self,
message: str = "Invalid date format",
formats: list[str] = ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"],
) -> None:
self._message = message
self._formats = formats

def validate(self, input_date) -> None:
"""Check if the user's date input is valid and well-formatted.

This method is used internally by `prompt_toolkit <https://python-prompt-toolkit.readthedocs.io/en/master/>`_.

See Also:
https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html?highlight=validator#input-validation

"""

for form in self._formats:
try:
return datetime.strptime(input_date.text, form)
except ValueError:
continue

raise ValidationError(
message=self._message,
cursor_position=input_date.cursor_position,
)
42 changes: 42 additions & 0 deletions docs/pages/validator.md
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,45 @@ result = inquirer.text(message="Age:", validate=NumberValidator()).execute()
```

</details>

### DateValidator

```{eval-rst}
.. autoclass:: InquirerPy.validator.DateValidator
:noindex:
```

<details>
<summary>Classic Syntax</summary>

```python
from InquirerPy import prompt
from InquirerPy.validator import DateValidator

result = prompt(
[
{
"type": "input",
"message": "Date of birth:",
"validate": DateValidator(
message="Invalid date format",
formats=["%Y-%m-%d"]
),
}
]
)
```

</details>

<details open>
<summary>Alternate Syntax</summary>

```python
from InquirerPy import inquirer
from InquirerPy.validator import NumberValidator

result = inquirer.text(message="Date of birth:", validate=DateValidator()).execute()
```

</details>
18 changes: 18 additions & 0 deletions tests/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,21 @@ def test_numberValidator(self):
self.assertRaises(ValidationError, validator.validate, self.document)
validator = NumberValidator(float_allowed=True)
self.execute_success_case(validator, "test_numberValidator")

def test_dateValidator(self):
validator = DateValidator()
self.document._text = "2042-04-02"
self.execute_success_case(validator, "test_dateValidator")
self.document._text = "0001-12-12"
self.execute_success_case(validator, "test_dateValidator")
self.document._text = "11-12-11"
self.assertRaises(ValidationError, validator.validate, self.document)
self.document._text = "1212-12-12 12:12:12"
self.execute_success_case(validator, "test_dateValidator")
self.document._text = "1212-12-12T12:12:12"
self.execute_success_case(validator, "test_dateValidator")
self.document._text = "2023-02-29"
self.assertRaises(ValidationError, validator.validate, self.document)
validator = DateValidator(formats=["%d/%m/%Y"])
self.document._text = "28/02/2023"
self.execute_success_case(validator, "test_dateValidator")