You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a basic field coerces a string form data value into a stronger type it can raise an error message. For example, IntegerField adds an error message Not a valid integer value. if the value cannot be parsed as an integer. It would be useful to be able to customise this error message but it is hardcoded into the field.
>>>importwtforms>>>classF(wtforms.Form):
... foo=wtforms.IntegerField(message="Enter foo as a number")
>>>f=F(foo="bar")
>>>f.validate()
False>>>f.errors
{'foo': ['Enter foo as a number']}
This blog post details how the error message can be customised using i18n, but that is rather laborious. Another workaround is to extend the field class:
classCustomMessageIntegerField(IntegerField):
""" An integer field that allows the error message for invalid values to be customised. """def__init__(
self,
label: str|None=None,
validators: tuple[Callable[[BaseForm, CustomMessageIntegerField], object], ...] |list[Any] |None=None,
invalid_message: str="Not a valid integer value.",
**kwargs: Any,
):
super().__init__(label, validators, **kwargs)
self._invalid_message=invalid_messagedefprocess_data(self, value: Any) ->None:
ifvalueisnotNone:
self._check_valid(value)
super().process_data(value)
defprocess_formdata(self, valuelist: list[Any]) ->None:
ifvaluelist:
self._check_valid(valuelist[0])
super().process_formdata(valuelist)
def_check_valid(self, value: Any) ->None:
try:
int(value)
exceptValueError:
raiseValueError(self._invalid_message)
Although this feels like a lot of work for something that could be provided by the library.
This issue is applicable for the following basic fields:
IntegerField
DecimalField
FloatField
DateTimeField
DateField
TimeField
WeekField
Environment
Python version: 3.12.1
wtforms version: 3.1.2
The text was updated successfully, but these errors were encountered:
When a basic field coerces a string form data value into a stronger type it can raise an error message. For example,
IntegerField
adds an error messageNot a valid integer value.
if the value cannot be parsed as an integer. It would be useful to be able to customise this error message but it is hardcoded into the field.Actual Behavior
Expected Behavior
This blog post details how the error message can be customised using i18n, but that is rather laborious. Another workaround is to extend the field class:
Although this feels like a lot of work for something that could be provided by the library.
This issue is applicable for the following basic fields:
IntegerField
DecimalField
FloatField
DateTimeField
DateField
TimeField
WeekField
Environment
The text was updated successfully, but these errors were encountered: