my RegexValidator seems to be working, because if the phone_number is entered in the wrong format, the form is not saved, but the error message is not showing up. If the format is according with regex, then form is saved. I checked the post Django regex validator message has no effect and included code attribute, but it did not change anything. It looks like something is missing, but I can not figure out what.My models.py and forms.py are below:
#models.py
from django.db import models
from django.core.validators import RegexValidator
class Notification(models.Model):
sender = models.EmailField(max_length = 100)
status = models.CharField(max_length = 50)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
message_info = models.TextField(max_length = 1000)
def __str__(self):
return self.message_info[:100]
class ScheduleNotification(Notification):
company = models.CharField(max_length = 50)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+79999999999'. Up to 15 digits allowed.",
code="invalid")
phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=False)
def __str__(self):
return self.sender
#forms.py
from django import forms
from .models import Notification, ScheduleNotification
...
class ScheduleNotificationForm(forms.ModelForm):
class Meta:
fields = ['sender', 'company', 'phone_number', 'message_info']
labels = {
"sender": "your email:",
"company": "your company:",
"phone_number": "your mobile:",
"message_info": "type your message:"
}