I'm using WTForms to display and validate form input. I use a DecimalField
for a money amount input, which works fine when inserting a value with a dot as a decimal separator. Since this website will be used in continental Europe however, I also want to allow a comma as a decimal separator. This means that both "2.5" and "2,5" should result in a value meaning "two and a half".
When I input a value with a comma, I get an error saying 'Not a valid decimal value'
. How can I accept both dots and commas as decimal separators with WTForms?
I know I can use Babel to use locale-based number formatting, but I don't want that. I specifically want to accept both a dot and a comma as separator values.
Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes. Tip: When you want to use the system separators again, select the Use system separators check box.
Click File | Options. In the pane on the left, click User Interface. In the pane on the right, scroll to the bottom and set the Decimal separator to Period (or Comma). Click OK and the decimal separators will be converted throughout the program.
Both a comma and a period (or full-stop) are generally accepted decimal separators for international use.
Decimal point and decimal comma are also common names for the decimal separator. For example, 9.5 means nine and one half in English speaking countries, while in many European countries, the same number might be written as 9,5.
You can subclass DecimalField
and replace commas with periods before the data is processed:
class FlexibleDecimalField(fields.DecimalField):
def process_formdata(self, valuelist):
if valuelist:
valuelist[0] = valuelist[0].replace(",", ".")
return super(FlexibleDecimalField, self).process_formdata(valuelist)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With