Skip to content

Instantly share code, notes, and snippets.

@brettinternet
Last active April 11, 2023 19:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettinternet/bad263d69c94a3a6b3e94c2b29410c6d to your computer and use it in GitHub Desktop.
Save brettinternet/bad263d69c94a3a6b3e94c2b29410c6d to your computer and use it in GitHub Desktop.
phone number regex validator
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.core.validators import RegexValidator
# ...
class User(AbstractBaseUser):
# ...
phone_number = models.CharField(
max_length=16,
blank=True,
null=True,
validators=[
RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format '+123456789'. Up to 15 digits allowed."
),
],
)
@brettinternet
Copy link
Author

Great write-up on setting up a custom User/models.py

https://afropolymath.svbtle.com/authentication-using-django-rest-framework

@tyler-weiss
Copy link

Don't ask me how I landed here (not quite sure myself).
Anyway, a random comment but I believe your validators list needs closure with a ']' instead of a '}'.

@brettinternet
Copy link
Author

@tyler-weiss Thanks! 😁

@saeedrezaghazanfari
Copy link

tanx 😍

@thezeeshann
Copy link

@brettinternet How do I pass the regex message to my Django model forms? and how do I show an error message on my HTML form?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment