django regexvalidator example

from django.core.validators import RegexValidator
from django.db import models
PHONE_NUMBER_REGEX = RegexValidator(r'^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$', 'only valid email is required')
class SomeClass(models.Model):
  phone =  models.CharField(max_length=14, validators=[PHONE_REGEX])
  

Here is what the above code is Doing:
1. We created a validator that checks if the phone number is valid or not.
2. We created a model field that uses the validator.
3. We created a model that uses the field.
4. We created an instance of the model.
5. We tried to save the instance.
6. We got an error.

The error is because the phone number is not valid.

To fix this, we need to change the phone number to a valid one.

We can do this by changing the phone number to a valid one:

class SomeClass(models.Model):
phone = models.CharField(max_length=14, validators=[PHONE_REGEX])

def __str__(self):
return self.phone

def save(self, *args, **kwargs):
self.phone = “+1-212-555-1212”
super(SomeClass, self).save(*args, **kwargs)

Now, when we try to save the instance, it will save without any errors.