简体   繁体   中英

Django RegexValidator Not working as expected

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

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]) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM