Django RegexValidator Not working as expected

2019-09-15 04:09发布

I'm stuck with the RegexValidator Class.

I'm trying to allow input of some defined HTML(p, ul, li) tags in a Character Field. The following Regex does exactly what I need but I'm having difficulty implementing it.

    <\/?(?!p|ul|li)[^/>]*>

I'm trying to implment it into my Django model in the following way:

     description = models.CharField(max_length = 255, validators=[
                                        RegexValidator(
                                            regex =  r'<\/?(?!p|ul|li)[^/>]*>',
                                            message = 'Disallowed Tags',
                                            code = 'DISALLOWED_TAGS',
                                        ),
                                    ],
                               )

I'm using Django 1.6. When I implement the above code, it seems that all form submissions (Using Admin Interface) fail validation.

Any ideas?

Thanks

1条回答
该账号已被封号
2楼-- · 2019-09-15 04:45

Do your own validator and if the regexp matches throw an error since it shouldn't be allowed.
here more info about validator.

import re
from django.core.exceptions import ValidationError

def test(val):
    if re.match('<\/?(?!p|ul|li)[^/>]*>', val):
        raise ValidationError('Disallowed Tags')

class Foo(models.Model):
    name = models.CharField(max_length = 150, validators=[test]) 
查看更多
登录 后发表回答