Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Field Regex Validation

Tags:

regex

django

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
like image 954
Eduardo Alves Avatar asked May 29 '14 19:05

Eduardo Alves


1 Answers

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])
like image 135
S.Ali Avatar answered Oct 13 '22 00:10

S.Ali