Django Field Regex Validation

django, regex

Solution

You can alter it to the below given code to see it working

hashtag_validator = CharField(
        max_length=50,
        required=True, #if you want that field to be mandatory
        validators=[
            RegexValidator(
                regex='^[#](\w+)$',
                message='Hashtag doesnt comply',
            ),
        ]
    )

Hope that helps!!

If that is causing problem you can try writing your own validator

from django.core.exceptions import ValidationError
import re
def validate_hash(value):
    reg = re.compile('^[#](\w+)$')
    if not reg.match(value) :
        raise ValidationError(u'%s hashtag doesnot comply' % value)

and change your model field to

hashtag_validator = models.Charfield(validators=[validate_hash])

Problem

I am trying to create a model to store an hashtag. The validator doesn't seem to be working, making the field accept all inputs, and I can't find the solution. Here is my model: ``` class Hashtags(models.Model): hashtag_validator = RegexValidator(r'^[#](\w+)$', "Hashtag doesn't comply.") hashtag_id = models.AutoField(primary_key=True) hashtag_text = models.CharField(max_length=100, validators=[hashtag_validator], unique=True) def get_id(self): return self.hashtag_id def get_text(self): return self.hashtag_text ```

Original source