I am creating a simple django app where you can create recipes with ingredients. On my RecipeCreate view I have a simple formset with a select input (where you select a product) and a input type="number" with the product count. So my form and model are quite simple:
class Ingredient(models.Model):
product = models.ForeignKey(Product)
count = models.DecimalField(max_digits=4, decimal_places=2)
class IngredientForm(forms.ModelForm):
class Meta:
model = Ingredient
fields = ('product', 'count')
Now when i want to display my recipe on my RecipeEdit view everything loads fine except for the count input. I get the following jQuery validation error:
The specified value "12,00" is not a valid number. The value
must match to the following regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)?
Because I'm writing a Polish website I would like to have our national standard decimal separator, which is a , not a . (but the dot should also be a separator).
One of the solutions would be to use an input type="text" but it would mean I have to validate my number manually, which is troublesome.
Is there any way to pass my number 12,00 so that it is accepted by the input field. Probably changing/overwriting the standard jQuery validation? But I will accept any good suggested solution.
Another curious fact is that when I write manually 12,00 or 12.00 and submit my form, my form is valid and my Ingredient count field has a value od 12 which is what I desire. It's another pro for the input type="number".
You could set your locale decimal separator
UPDATE:
Didnt saw it is jquery related,
you could create new validator class for comma numbers for instance
jQuery.validator.addMethod("commanumber", function (value, element) {
return this.optional(element) || /^(\d+|\d+,\d{1,2})$/.test(value);
}, "Please specify the correct number format");
or even extend regex to support . also
Ok, I've done something like this. First of all I am using an input type="text". Then using jQuery.numeric() I convert my input so that it only accepts numbers, and a , as decimal separator.
$("#field_id").numeric({ decimal : "," });
Now every time i submit my form I have some code that converts my , into . so that it fits the backend logic:
$('#recipe-form').on('submit', function(){
$('.convert-separator').each(function () {
$(this).val($(this).val().replace(',','.'));
});
this.submit();
});
But I think it's not the best solution. I think there must be a possibility to use the input type="number" field with a , separator.
You can convert the count value in your jQuery code:
dotCount = count.toString().replace(',', '.');
This replaces the comma with a dot