Skip to content

cron

validators.cron.cron(value)

Return whether or not given value is a valid cron string.

Examples:

>>> cron('*/5 * * * *')
# Output: True
>>> cron('30-20 * * * *')
# Output: ValidationError(func=cron, ...)

Parameters:

Name Type Description Default
value str

Cron string to validate.

required

Returns:

Type Description
Literal[True]

If value is a valid cron string.

ValidationError

If value is an invalid cron string.

Source code in src/validators/cron.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@validator
def cron(value: str, /):
    """Return whether or not given value is a valid cron string.

    Examples:
        >>> cron('*/5 * * * *')
        # Output: True
        >>> cron('30-20 * * * *')
        # Output: ValidationError(func=cron, ...)

    Args:
        value:
            Cron string to validate.

    Returns:
        (Literal[True]): If `value` is a valid cron string.
        (ValidationError): If `value` is an invalid cron string.
    """
    if not value:
        return False

    try:
        minutes, hours, days, months, weekdays = value.strip().split()
    except ValueError as err:
        raise ValueError("Badly formatted cron string") from err

    if not _validate_cron_component(minutes, 0, 59):
        return False
    if not _validate_cron_component(hours, 0, 23):
        return False
    if not _validate_cron_component(days, 1, 31):
        return False
    if not _validate_cron_component(months, 1, 12):
        return False
    if not _validate_cron_component(weekdays, 0, 6):
        return False

    return True