Nepo Znat
Nepo Znat

Reputation: 3270

form clean method vs model clean method vs model field validator

I have a model with the field facebook_link.

With the help of a regular expression I want to validate if this link is really a facebook link.

The user can enter the facebook link in a form.

Should I place my validation in the clean method of the form field,

in the clean method of the model field

or should I use a a custom validator

Upvotes: 3

Views: 137

Answers (2)

mistiru
mistiru

Reputation: 3366

You should use a RegexValidator, place it in your model field definition, and use a ModelForm so that it will call the clean method on your model field.

Upvotes: 1

Jonah Bishop
Jonah Bishop

Reputation: 12581

If I read the documentation correctly, I think the answer to your question is none of the above. According to the validators documentation, a built-in RegexValidator is available for you to validate data using regular expressions. This is likely what you should use (don't reinvent the wheel).

Technically speaking, however, I think validators are the right place to put this kind of logic, precisely because they can be used either on forms or models. That re-usability alone makes them worthwhile.

Upvotes: 1

Related Questions