diff --git a/homeassistant/components/input_datetime/__init__.py b/homeassistant/components/input_datetime/__init__.py index 84a7fb89fe1..2713eef17f8 100644 --- a/homeassistant/components/input_datetime/__init__.py +++ b/homeassistant/components/input_datetime/__init__.py @@ -81,6 +81,30 @@ def has_date_or_time(conf): raise vol.Invalid("Entity needs at least a date or a time") +def valid_initial(conf): + """Check the initial value is valid.""" + initial = conf.get(CONF_INITIAL) + if not initial: + return conf + + if conf[CONF_HAS_DATE] and conf[CONF_HAS_TIME]: + parsed_value = dt_util.parse_datetime(initial) + if parsed_value is not None: + return conf + raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a datetime") + + if conf[CONF_HAS_DATE]: + parsed_value = dt_util.parse_date(initial) + if parsed_value is not None: + return conf + raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a date") + + parsed_value = dt_util.parse_time(initial) + if parsed_value is not None: + return conf + raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a time") + + CONFIG_SCHEMA = vol.Schema( { DOMAIN: cv.schema_with_slug_keys( @@ -93,6 +117,7 @@ CONFIG_SCHEMA = vol.Schema( vol.Optional(CONF_INITIAL): cv.string, }, has_date_or_time, + valid_initial, ) ) }, diff --git a/tests/components/input_datetime/test_init.py b/tests/components/input_datetime/test_init.py index 39497e1164c..0a968caf67f 100644 --- a/tests/components/input_datetime/test_init.py +++ b/tests/components/input_datetime/test_init.py @@ -744,3 +744,30 @@ async def test_timestamp(hass): finally: dt_util.set_default_time_zone(ORIG_TIMEZONE) + + +@pytest.mark.parametrize( + "config, error", + [ + ( + {"has_time": True, "has_date": True, "initial": "abc"}, + "'abc' can't be parsed as a datetime", + ), + ( + {"has_time": False, "has_date": True, "initial": "abc"}, + "'abc' can't be parsed as a date", + ), + ( + {"has_time": True, "has_date": False, "initial": "abc"}, + "'abc' can't be parsed as a time", + ), + ], +) +async def test_invalid_initial(hass, caplog, config, error): + """Test configuration is rejected if the initial value is invalid.""" + assert not await async_setup_component( + hass, + DOMAIN, + {DOMAIN: {"test_date": config}}, + ) + assert error in caplog.text