Question

I've got this model class:

class ItemTag(models.Model):

  name_regex = re.compile(r'[^,]')
  name = models.CharField('Tag Name', max_length = 20, unique = True,
                          validators=[RegexValidator(regex=name_regex)] )
  class Meta:
    ordering = ['name']

I need to use the validator to reject strings with commas in them. I expected re.compile(r'[^,]') to do this but it's not.

When I change it to re.compile(r'[,]') it requires the comma, which is what I expected, but the negation of the character class doesn't seem to work as expected and I haven't been able to find any explanation in the documentation.

I use these applications:

Python 2.6.5 Django 1.4.5

Was it helpful?

Solution

[^,] means "one character, any character except a ,".

So your regex was checking that there was at least one non-comma character.

You can use this instead to ensure only non-comma characters are in your string:

^[^,]+$

^$ are anchors matching the beginning and end of the string respectively.

OTHER TIPS

You should use the following regex:

name_regex = re.compile(r'^[^,]*$')

This checks the whole string to ensure that none of the characters are a ,

Use negative lookahead (?!.*[,])

class ItemTag(models.Model):

  name_regex = re.compile("^(?!.*[,]).*$")
  name = models.CharField('Tag Name', max_length = 20, unique = True,
                          validators=[RegexValidator(regex=name_regex)] )
  class Meta:
    ordering = ['name']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top