'How to set min length for models.TextField()?
There seem to be a max_length for CharField only. But how about min_length for a TextField(), is there a way to enforce 100 characters in the TextField?
Solution 1:[1]
You would use a custom validator, specifically MinLengthValidator
Solution 2:[2]
When declaring a Django form
cell_phone=forms.CharField(max_length=10,min_length=10);
When rendering a form field in Django template
{% render_field form1.cell_phone minlength="10" maxlength="10" %}
Underscore is confusing
Solution 3:[3]
For models.Models field validation:
from django.db.models import TextField
from django.db.models.functions import Length
TextField.register_lookup(Length, 'length')
class Foo(models.Mode):
text_field_name = models.TextField()
class Meta:
constraints = [
models.CheckConstraint(
check=Q(text_field_name__length__gte=10),
name="text_field_name_min_length",
)
]
Using constrains will create validation on the database level (I think), which will be called on save()
This also works for CharField.
Solution 4:[4]
in this case you need to import the MinLengthValidator resource from django.core.validators, which will look like this:
from django.core.validators import MinLengthValidator
To use the resource, the model must be written as follows:
variable = models.TextField(
validators=[
MinLengthValidator(50, 'the field must contain at least 50 characters')
]
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Braiam |
| Solution 2 | Aseem |
| Solution 3 | Braiam |
| Solution 4 | Felipe Gabriel Souza Martins |
