Form classes are intended (IMO) for submitted data against rules. For example: are passwords equal, is end date later than start date.
submitted data--->|Form|
Is it okay for Form classes to validate submitted data against data retrieved from a database as well? This seems like a responsibility issue, the Form class should responsible for validating and cleaning the submission alone, and checking against the DB belongs outside the class.
submitted data--->|Form|<---data from DB
Here is my example in WTForms in Python: it checks if the user id is an integer, then queries the DB to verify that it exists.
class ClientForm(Form):
name = StringField(validators=[DataRequired(message="Invalid value")])
user = IntegerField(validators=[DataRequired(message="Invalid value")])
zone = IntegerField(validators=[AnyOf([i[0] for i in ZONES], message="Invalid value")])
#validate user as real
def validate_user(form, field):
user = db.session.query(User).filter(User.id==form.user.data).first()
if not user:
raise ValidationError('Invalid user')
The upside of adding this check to the form is convenience, WTForms handles all aspects of errors, even rendering them:
form = ClientForm(post_data)
if not form.validate():
# render the form again with errors highlighted
return render("client_registration_form.html", form=form)
else:
return render("success.html")