Question

I have a IntegerField, where I want the input to only accept a value of 11 digits/numbers.

I have tried to make a regex validator on the field, but my problem is when I try to make a model form with the field. I only get a validation-error if the value is 10 digits or less, but if I try a value with 12 digits and upwards, I don't get any validation error.

Here is my model field:

number =  models.IntegerField(max_length=11, validators=[RegexValidator(r'\d{11,11}','Number must be 11 digits','Invalid number')])

How can I make it so I get a validation error if the value is more than 11 digits?

Was it helpful?

Solution

Not sure about django syntax, but you have to use anchors:

r'^\d{11}$'

OTHER TIPS

Consider using the min_length kwarg – it works exactly as you would imagine it does:

class YourModel(models.Model):
    number = models.IntegerField(max_length=11, min_length=11,
        validators=[RegexValidator(r'\d{11,11}',
            'Number must be 11 digits', 'Invalid number')])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top