Input Text pattern expression not being enforced

I have the following input_text defined. However this mask isn’t being enforced. I can enter any value, instead of requiring a 4 digit number. Is not the pattern supposed to do exactly this?

foobar:
  name: ''
  pattern: '[0-9]{4}'

You can enter any value but only a 4 digit value will be accepted.

If I create the input text exactly as you have shown, I have the exact same result … I can enter anything, and any entry is accepted. I can enter ‘abcdefg’, for example, and it will update the state to ‘abcdefg’. If you have since found a solution, please share. Thanks.

TLDR: Workaround

As of right now pattern matching in input text doesn’t prevent changing the value to an invalid format, it only shows a warning in the lovelace card in the form of ared outline and a nudg animation when the input is confirmed. This may be broken or it may be the intended functionality, I couldn’t find anything in the docs stating what exactly the effect is supposed to be.

In any case, a workaround is to create an automation that triggers on state change of the entity in question, has a condition that is true when the state does not match the intended format (template → regex), and an action to reset the state to a default, to a prevevious value, or potentially even try to fix the error.

As an example, this is what I have just set up and is working as expected:

alias: Manual Add Time Validation
description: "Detect if state is changed to invalid format, inform user, and reset to default value."
trigger:
  - platform: state
    entity_id:
      - input_text.manual_add_time
condition:
  - condition: not
    conditions:
      - condition: template
        value_template: >-
          {{ states('input_text.manual_add_time') | string is
          match('[0-9]+:[0-9]+:[0-9]+(?:\.[0-9]+)?') }}
action:
  - service: input_text.set_value
    data:
      value: Invalid Format
    target:
      entity_id: input_text.manual_add_time
  - delay:
      hours: 0
      minutes: 0
      seconds: 3
      milliseconds: 0
  - service: input_text.set_value
    data:
      value: Use "HH:MM:SS"
    target:
      entity_id: input_text.manual_add_time
  - delay:
      hours: 0
      minutes: 0
      seconds: 3
      milliseconds: 0
  - service: input_text.set_value
    data:
      value: "00:00:00"
    target:
      entity_id: input_text.manual_add_time
mode: single
1 Like