8👍
I see three ways of achieving this:
Option 1
Use a RegEx validator inside your PhoneNumberField
:
from django.core.validators import RegexValidator
...
phone = PhoneNumberField(null=True, validators=[RegexValidator(r'^\d{3}-\d{3}-\d{4}$')])
Option 2
According to documentation, you can set the format to be NATIONAL
and then set the region. As such, you can use in your settings:
PHONENUMBER_DB_FORMAT = 'NATIONAL'
PHONENUMBER_DEFAULT_REGION = 'US'
Option 3
Use a RegEx validator, but change your field to be a CharField
.
from django.core.validators import RegexValidator
...
phone = models.CharField(null=True, validators=[RegexValidator(r'^\d{3}-\d{3}-\d{4}$')])
3👍
As documentation says:
Recommended is one of the globally meaningful formats ‘E164’, ‘INTERNATIONAL’ or ‘RFC3966’. ‘NATIONAL’ format require to set up PHONENUMBER_DEFAULT_REGION variabl
So you need to setup your default region. eg: PHONENUMBER_DEFAULT_REGION='US'
in your settings.py
.
0👍
Use the regular expression to allow hyphen in between. It will allow these formats
* 123-456-7890
* 333-333-4444
* 1234567890
* 123456789
* 123-4567-890
* 14157059247
Regular expression ^\d{3}-\d{3}-\d{4}$
- [Django]-Searching for a project skeleton for Chef + Django on Linux
- [Django]-Django Temporary Images
- [Django]-Validation Error with Multiple File Uploads in Django via Ajax
- [Django]-ImportError: No module named books.models