0

how else can i frame this django custom validation function to validate US phone number other than try and except block

def validate(value):
        if re.match(r"[+]?[1\s-]*[\(-]?[0-9]{3}[-\)]?[\s-]?[0-9]{3}[\s-]?[0-9]{4}",value):
            return True
        else:
            return False
Itriedit
  • 71
  • 1
  • 7
  • What do you mean you are already running it without try except. – Ahtisham Feb 01 '22 at 04:18
  • any other ways otherthan above code and try except – Itriedit Feb 01 '22 at 04:26
  • This is a Python related question, not Django. As I have said in your previous posts, you need to learn the basics of Python and programming in general. I'm not trying to discourage you from asking questions, but you have been trying to get help for the same function with different parts for the past 3 days, and these are very trivial tasks as well. We all have started from where you are, and it will help you more if you spend time to build your foundations in programming. – Naeem Khan Feb 01 '22 at 04:26
  • @NaeemKhan Thanks for the suggestion but nothing is striking in my head i am trying – Itriedit Feb 01 '22 at 04:28
  • `match` will return string if match otherwise `None`. – Ahtisham Feb 01 '22 at 04:28
  • @Ahtisham I tried like this it returns nothing – Itriedit Feb 01 '22 at 04:29
  • Sorry my bad i have updated the comment – Ahtisham Feb 01 '22 at 04:32

1 Answers1

0

In order for a function to be used as a validator for Django fields, it needs to raise a ValueError if given an invalid value.

Here's an example of your validator in validators.py, adapted to follow this convention and use re.compile() to speed up your regular expression matching:

# validators.py
import re

# Create a compiled regular expression to speed things up.
# You can also break your string into two strings, one per
# line, to improve readability:
PHONE_REGEX = re.compile(r"[+]?[1\s-]*[\(-]?[0-9]{3}[-\)]?[\s-]?"
                         r"[0-9]{3}[\s-]?[0-9]{4}")

def validate_phone_number(value):
    """Validates that a phone number matches the format
    123 456 7890, with optional dashes between digit groups
    and parentheses around the area code.
    """
    if not PHONE_REGEX.match(value):
        raise ValueError(f'{value} must be in the format 123 456 7890')

You can use this validator in models.py as follows:

# models.py
from django.db import models
from .validators import validate_phone_number

class YourModel(models.Model):
    phone_number = models.CharField(max_length=30, validators=[validate_phone_number])

A few more notes:

  • Review this StackOverflow question to get better regular expressions for your phone numbers.
  • Note that not all phone numbers have ten digits. If your web site is intended for an international audience, you'll have to accept their phone numbers too.
Jeff Booth
  • 461
  • 2
  • 5
  • Thanks for the answer can you please elaborate on how does adding re.compile speed things us like how it differs from re.match('regex expression',value) – Itriedit Feb 01 '22 at 05:03
  • @Itriedit if you will look this up in docs you can find it yourself. – Vishal Singh Feb 01 '22 at 05:05
  • @Itriedit Whenever you call `re.match()`, it has to (a) compile the regular expression, then (b) search for a match in the provided string. `re.compile` lets your program do step (a) only once, instead of every time you search for a match. You can read more about `re.compile()` [here](https://docs.python.org/3/library/re.html#re.compile). Please mark this answer as accepted, so I can get credit for it! – Jeff Booth Feb 01 '22 at 05:25