How to accept both a period and a comma as a decimal separator with WTForms?

I use WTForms to display and validate form input. I use DecimalField to enter the amount of money, which works great when pasting a value with a dot as a delimiter with delimiters. Since this website will be used in continental Europe, I also want to allow the 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 enter a semicolon, I get the error message 'Not a valid decimal value' . How can I accept both periods and commas as decimal separators using WTForms?


I know that I can use Babel to use language-based number formatting, but I don't want that. I specifically want to accept both the period and the comma as the separator values.

+5
source share
1 answer

You can subclass DecimalField and replace commas with periods before data processing:

 class FlexibleDecimalField(fields.DecimalField): def process_formdata(self, valuelist): if valuelist: valuelist[0] = valuelist[0].replace(",", ".") return super(FlexibleDecimalField, self).process_formdata(valuelist) 
+6
source

Source: https://habr.com/ru/post/1211561/


All Articles