pallets-eco / wtforms

A flexible forms validation and rendering library for Python.
https://wtforms.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.51k stars 395 forks source link

Should forms be validated without request data? #806

Open azmeuk opened 1 year ago

azmeuk commented 1 year ago

Recent tickets (#804 , #769) suggest that people want to validate forms without request data. This means people want to validate forms that are not initialized with real HTML form data.

Currently the documentation is not very clear whether this is allowed or not. Most of the time the code works, but sometimes not and I believe this is the cause of some bug reports. If we decide this is not supported, then we might want to document this. If we decide this is supported, then we need to list the implications in the code. I can think at least of making the validators work with python native types (and not just request form strings).

I can think at least of two situation where that could be useful, though I never met it directly.

Do you people have met that kind of situations in real-world use-cases?

Any thought on whether this should be supported in wtforms?

HK-Mattew commented 1 year ago

My humble opinion is that all data passed to the Form should be validated. Either in formdata= or data=

Because my use case is: I render the form in HTML, but I send the form data via ajax. Then I load the data into the backend using MyForm(data=data) and want to validate this data.

Daverball commented 1 year ago

I think it is valuable to distinguish between form data and object data, especially for things like InputRequired vs. DataRequired which are different requirements.

That being said, I think the main issue here is how Optional/Required are implemented generically as validators in WTForms. This never really made a whole lot of sense to me and I think is mostly an artifact of wanting to avoid having redundant self.data is None in every validator in the validation chain.

It would simplify things a lot if it instead was a property of the field. That means the field can deal with whether or not expects data to be present in the various process_x and validate methods (and even in custom validators). This would allow more accurate data presence validation, that's dependent on the type of the field as well, take e.g. IntegerField. DataRequired will currently reject 0, even though that doesn't really make sense.

We could keep things as flexible as they are right now with validators by making required into an optional callback, rather than a static boolean value and have a separate property for the various types of data, i.e. data_required raw_data_required object_data_required

tqian86 commented 1 month ago

Thanks @Daverball for the explanation. We ran into this issue, and switching to use DataRequired works for our use case.