ryonistic
ryonistic

Reputation: 165

How to disallow specific character input to a CharField

I have a model in which I want to disallow the input of special characters(+,-,/,%, etc) in the title field:

class Article(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.title

Can I accomplish this in the model itself? Or do I have to do something with the forms.py so that users arent able to post a form with special chars in the title. How exactly can I accomplish this?

Upvotes: 7

Views: 2551

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

You can add a validator with the validators=… parameter [Django-doc] and work with an inverse regex:

from django.core.validators import RegexValidator

class Article(models.Model):
    title = models.CharField(
        max_length=100,
        validators=[RegexValidator('[+-/%]', inverse_match=True)]
    )
    # …

Upvotes: 9

Related Questions