[Answer]-How to match a 'word' using regex in django/python


You’ll have to make it a separate validator; you are passing the second regular expression into the RegexValidator() object as a message.

Just use a simple function that validates the value; you don’t need a regular expression here, you want to invalidate values instead. Writing a regular expression that matches only on a negative gets complicated and is not what you want to do here:

from django.core.exceptions import ValidationError

forbidden = {'login', 'logout'}

def not_forbidden(value):
    if value in forbidden:
        raise ValidationError(u'%s is not permitted as a username' % value)

username = models.CharField(max_length=14, blank=False, unique=True, validators=[
        validators.RegexValidator(r'^[^:;\'\"<>!@#$%|\^&\*\(\)~`,.?/=\-\+\\\{\}]? [\w]+$'),

See Writing validators.

Leave a comment