Jonas Fredriksson
Jonas Fredriksson

Reputation: 355

custom validator for charfield do not raise any error

I have done a validator that is supposed to check the input from a charfield:

def postnvali(value):
    
    if not value.isalnum():
        raise ValidationError(_('postnummer måste vara siffror'))

it is used in the following model:

class Adress(Model):

    street=CharField(max_length=100)
    snumb=CharField(max_length=15)
    town=CharField(max_length=100)
    postn=CharField(max_length=5,validators=[postnvali])
    
    def __str__(self):
        return 'city: ' + self.town

    class Meta:
        ordering=('street','town')

but when using admin and entering the wrong format, nothing happens, no error message. why?

Upvotes: 0

Views: 50

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

The function str.isalnum(…) returns:

Return True if all characters in S are alphanumeric.

This means that the characters can be numbers (0-9), or alphabetical (A-Za-z), but based on the error message, you want to only allow digits. You thus should use The function str.isdigit(…):

Return True if all characters in the string are digits and there is at least one character, False otherwise.

So we can rewrite the validator to:

def postnvali(value):
    
    if not value.isdigit():
        raise ValidationError(_('postnummer måste vara siffror'))

Upvotes: 1

Related Questions