Skip to content

Commit ce692fa

Browse files
author
lichuang9890-star
committed
fix: show custom error messages when hide_input=True
Previously, when hide_input=True and a type's convert() raised a UsageError (e.g. BadParameter), the custom error message was replaced with a generic 'Error: The value you entered was invalid.' message. The hide_input flag should only affect whether the input value is echoed during typing, not whether custom validation error messages are displayed. Custom error messages from type validation are written by the developer and do not contain the secret input value. Fixes #2809
1 parent 04ef3a6 commit ce692fa

2 files changed

Lines changed: 28 additions & 4 deletions

File tree

src/click/termui.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,7 @@ def prompt_func(text: str) -> str:
177177
try:
178178
result = value_proc(value)
179179
except UsageError as e:
180-
if hide_input:
181-
echo(_("Error: The value you entered was invalid."), err=err)
182-
else:
183-
echo(_("Error: {e.message}").format(e=e), err=err)
180+
echo(_("Error: {e.message}").format(e=e), err=err)
184181
continue
185182
if not confirmation_prompt:
186183
return result

tests/test_utils.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,3 +746,30 @@ def test_make_default_short_help(value, max_length, alter, expect):
746746

747747
out = click.utils.make_default_short_help(value, max_length)
748748
assert out == expect
749+
750+
751+
def test_hide_input_shows_custom_error(runner):
752+
"""With hide_input=True, custom error messages from type validation
753+
should still be displayed, not swallowed by a generic message."""
754+
755+
class StrictPassword(click.ParamType):
756+
name = "password"
757+
758+
def convert(self, value, param, ctx):
759+
if len(value) < 8:
760+
self.fail("Password must be at least 8 characters", param, ctx)
761+
return value
762+
763+
@click.command()
764+
@click.option(
765+
"--pw",
766+
prompt=True,
767+
hide_input=True,
768+
type=StrictPassword(),
769+
)
770+
def cmd(pw):
771+
click.echo(f"OK:{pw}")
772+
773+
result = runner.invoke(cmd, input="short\nlong_enough_pw\n")
774+
assert "Password must be at least 8 characters" in result.output
775+
assert "OK:long_enough_pw" in result.output

0 commit comments

Comments
 (0)