Home > other >  How else can i write this django custom validation othere than try and except
How else can i write this django custom validation othere than try and except

Time:02-01

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

CodePudding user response:

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.
  •  Tags:  
  • Related