newforms
newforms copied to clipboard
form with FloadField required=false passes validation with wrong value
I have a form with
amount : forms.FloatField({label: 'Amount', required: false, maxValue: 1}),
When I input there randome string, like 'asdfasdf' form.validate() returns true, form.cleanedData returns {amount: null}
When I input a big number, like 123 it throws me validating error "Ensure this value is less than or equal to 1."
Is it a correct behaviour ?
How are you getting user input into the form?
Having null
in cleaned data is consistent with providing an "empty" value for a required field, which indicates that 'asdfasdf'
might not actually have been set as input data when the form was validated:
> var TestForm= forms.Form.extend({
... amount: forms.FloatField({label: 'Amount', required: false, maxValue: 1})
... })
> var f = new TestForm({data: {amount: ''}})
> f.validate()
true
> f.cleanedData
{ amount: null }
> var f = new TestForm({data: {amount: 'asdfasdf'}})
> f.validate()
false
> f.cleanedData
{}
> f.errors().asText()
* amount
* Enter a number.
The behaviour of maxValue
is correct - if you wanted 123
to be a valid input, did you mean minValue
instead?
I've prepeared a jsfiddle with this error https://jsfiddle.net/23Lmvcc7/ try to enter some text into field, I'm recieving "This field is required" error insted of "Enter a number" Maybe newforms-bootstrap is the problem ?
Looks like this is due to this field using an <input type="number">
by default - according to the HTML5 spec, its value
must be set to an empty string when invalid, so newforms never sees the non-numeric input.
If the value of the element is not a valid floating-point number, then set it to the empty string instead.
You are right. I've fixed my issue by moving _onSubmit function from button onClick to form onSubmit. Now browser validates my field and I cant submit form with wrong values.
Maybe I'm wrong, but I remember developers of angularjs have fixed this problem. You can use number field with novalidate form and have a nice angularjs validating error.
PS Thanks for the great lib.