Search code examples
djangodjango-modelsdjango-validation

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?


Solution

  • 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)]
        )
        # …