Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot validate raw integer 0 with required IntegerField. #39

Open
m-martinez opened this issue Mar 18, 2015 · 3 comments
Open

Cannot validate raw integer 0 with required IntegerField. #39

m-martinez opened this issue Mar 18, 2015 · 3 comments

Comments

@m-martinez
Copy link

I'm having issues validating a required IntegerField when the JSON value passed is 0:

import wtforms_json
wtforms_json.init()

from wtforms import Form, IntegerField
from wtforms.validators import InputRequired

class MyForm(Form):
    a = IntegerField(validators=[InputRequired()])

# Works with > 0
form = MyForm.from_json({'a': 5})
assert form.validate()

# Does not work with value 0
form = MyForm.from_json({'a': 0})
assert form.validate()

# Works with string '0'
form = MyForm.from_json({'a': '0'})
assert form.validate()

Using wtforms 2.0.2

kvesteri added a commit that referenced this issue Mar 28, 2015
@kvesteri
Copy link
Owner

Added a failing test case, no clue yet how to fix this.

@evansp01
Copy link

I believe that I understand the problem.

If you look at the input required validator in wtforms

https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py#L241

you see this code

if not field.raw_data or not field.raw_data[0]:

The raw data is expected to be a string, even in an integer field. The error occurs when we give it raw data which is not a string, and happens to evaluate to false.

If you convert integers to strings before giving them to the form (in fact you only need to convert 0, since it is the only integer which evaluates to false), then you pass the test case.

    if value is 0:
        value = str(value)

https://github.com/evansp01/wtforms-json/blob/hotfix/39-integer-validation/wtforms_json/__init__.py#L56

I'm not sure exactly how you would want to go about fixing this, since I noticed that if I converted all the integers to strings, I fail a bunch of your test cases with mismatches like

{a:'1'} != {a:1}

But that is what is going on.

Cheers,

Evan

@alanhamlett
Copy link
Contributor

Try patching Optional like #26.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants