Yunti
Yunti

Reputation: 7438

Regex validator on form seems to interfere with max_length validation on Charfield

I'm trying to validate input for a form field as a numbers only with 12-14 digits and which may have leading zeros.

However when I add the below regex validator for numbers to my form field it seems to interfere whenever there is a max_length set on the form and it fails validation.

only_numbers = RegexValidator(r'^\d{1,10}$')

mpan_lower = forms.CharField(label='some_label',
    help_text=mark_safe('Help text with link. '
                        '<a href="#">  Need more help?</a>'),
                        validators=[
                                     only_numbers,
                                 ],
                                 max_length=14,
                                 )

enter image description here

Upvotes: 0

Views: 362

Answers (1)

Alasdair
Alasdair

Reputation: 308799

r'^\d{1,10}$'

This regex will allow between 1 and 10 digits. The string 12345678901234 has 14 digits so the regex validator will not accept it.

If you want between 12 and 14 digits, then use:

r'^\d{12,14}$'

Alternatively, you could use r'^\d+$ (matches 1 or more digits), and validate the length another way (e.g. by setting min_length and max_length for your form field).

Upvotes: 1

Related Questions