I am wanting to allow only characters 0-9 for all characters entered into a Django CharField.
When I use RegexValidator() with regex = r'[^0-9]'. I can enter everything but 0-9 in the field. Actually, it will allow me to enter a strings like "word", "a4523", "!#$%#^%", and "5432bc", but not "4523".
If I take out the ^ and set regex = r'[0-9]' (see code below) then I can enter "4523", "5432bc", and "a4523" but not "word" or "!#$%#^%".
Removing the ^ seems to get me in the right direction, but not the full way. I do not want to use a PositiveSmallIntegerField because I want to treat the numeric input as a string.
class Number(models.Model):
number = models.CharField(
max_length=14,
validators=[
RegexValidator(
r'[0-9]',
'Only 0-9 are allowed.',
'Invalid Number'
),
MinLengthValidator(4),
MaxLengthValidator(14),
],
)
The regular expression
[^0-9]means to match a non-digit anywhere in the string. You probably meant to start with^[0-9], which requires a digit at the start of the string. For a complete solution, I think you want^[0-9]*$, which requires all characters in the string to be digits.