Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask form validation design

I'm not new to programming but I am new to Python and Flask. I have a design question regarding form validation.

I have a registration form that captures the user information as well as the company they belong to. The form then validates whether the email is already in use but I want to also validate whether or not the company has been signed up before. I don't want the same company to sign up more than once.

Trying to match solely on company name will likely cause issues because users don't necessarily spell things the same (ie: adding or omitting punctuation). My thought is to validate on the first X number of characters in the company name, the street address number, and zip code. If there is a match, the user isn't allowed to sign up and they will have to call in (or some other process to be determined).

Ok, the real question... Is it a better to add the validation to the WTF form? Or add a helper function in the model? I'm validating three fields and didn't know which was best practice.

EDIT - I'm really asking if I have to validate on more than one field, do I add it to the Form or with a helper function in the model?

Thanks for your assistance.

Jimmy

like image 646
Jimmymcdaniel Avatar asked Nov 11 '22 11:11

Jimmymcdaniel


1 Answers

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.

like image 99
joehand Avatar answered Nov 14 '22 22:11

joehand