[Solved]-Django Field Regex Validation

9๐Ÿ‘

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])
๐Ÿ‘คS.Ali

2๐Ÿ‘

Very late to the party so I doubt that this is still a problem for OP, but I will leave this here just for posterity and people that happen to come across this post. Probably you are instantiating and saving an object directly, e.g Hashtags(hashtag_text='invalid-tag').save(). This will not call the validators. The validators are only called when full_clean or clean is called, which is only done automatically if you go through a ModelForm. If you instantiate objects manually, either through the constructor or the object collection Hashtags.objects.create the validators will not be called.

๐Ÿ‘คPankrates

0๐Ÿ‘

In addition to S.Ali answer:

based on example from here

def uncvalidator(value):
    """Custom UNC path validator"""
    import re
    from django.utils.translation import gettext_lazy as _
    UNC_REGEX = r'^local.company/some/share'
    regex = re.compile(UNC_REGEX, re.IGNORECASE)
    if not regex.match(value):
        raise ValidationError(
            _('Entered path %(value)s is incorrect.'),
            params={'value': value},
              )

unc = models.CharField(
    validators=[uncvalidator],
)
๐Ÿ‘คgek

Leave a comment