Flask form validation design Flask form validation design flask flask

Flask form validation design


Validating using WTForms is likely better in this case. It will be easier to send an error message to the user.

In WTForms, it is easy to add a custom validator:

class MyForm(Form):company = TextField('Company', [Required()])def validate_company(form, field):    if len(field.data) > 50:        raise ValidationError('Name must be less than 50 characters')

In your case, however, this will not work because you want to do multiple fields. WTForms to the rescue! You can validate all of your company fields through a field enclosure. This will allow you to treat "company info" as one field and validate over each of them.

class CompanyForm(Form):    name = StringField('Company name', [validators.required()])    address    = StringField('Address', [validators.required()])class RegistrationForm(Form):    first_name   = StringField()    last_name    = StringField()    company = FormField(CompanyForm, [your_custom_validation])

You can also add uniqueness requirements to your DB model. Not sure what your database is, but MongoDB provides a unique_with requirement. But that won't do any validation, it will just throw an error if you try to create non-unique db entries.