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

Length Validator Broken when min=0 #872

Open
jb2170 opened this issue Dec 19, 2024 · 0 comments · May be fixed by #873
Open

Length Validator Broken when min=0 #872

jb2170 opened this issue Dec 19, 2024 · 0 comments · May be fixed by #873

Comments

@jb2170
Copy link

jb2170 commented Dec 19, 2024

PR incoming.

Actual Behavior

WTForm's Length validator incorrectly approves a missing string (aka field.data is None) when min=0, whereas it should fail validation.

I interpret min=-1 to mean 'no minimum length, permit None and the empty string '''

I interpret min=0 to mean 'minimum length 0, do not permit None, aka a missing field, but do permit the empty string '''

Serving the following app with $ gunicorn min-len-fail:app on the default localhost:8000

from flask              import Flask, request, jsonify
from wtforms            import Form, StringField
from wtforms.validators import Length

app = Flask(__name__)

class TestForm(Form):
    title = StringField("Title", validators = [Length(min=0)])

@app.route("/", methods = ["POST"])
def index():
    form = TestForm(request.form)
    if form.validate():
        return jsonify({"msg": "Success!", "title": form.title.data})
    else:
        return jsonify(form.errors), 400

Test POSTing title both as missing, and as the empty string, with curl

$ curl -sSL -d 'titl=' localhost:8000
{"msg":"Success!","title":null}
$ curl -sSL -d 'title=' localhost:8000
{"msg":"Success!","title":""}

The Length validator reports success for both cases, whereas it should fail the first.

Expected Behavior

With the PR incoming

$ curl -sSL -d 'titl=' localhost:8000
{"title":["Field must be at least 0 characters long."]}
$ curl -sSL -d 'title=' localhost:8000
{"msg":"Success!","title":""}

Environment

  • Python version: 3.12.7, Arch Linux
  • wtforms version: main branch (3.2.1)

Cause

class Length:
    ...
    def __call__(self, form, field):
        length = field.data and len(field.data) or 0
        ...

The default length of 0 is incorrect; it should be -1. And no we can't just change the 0 to a -1 in that awful x and y or z mess otherwise the empty string would incorrectly set length to -1.

I've added three tests for the Length validator to stress-test the difference between the None missing string and the '' empty string.

@jb2170 jb2170 linked a pull request Dec 19, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

1 participant