0

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:"
        }
Victor Di
  • 988
  • 10
  • 16
  • 2
    Where do you use your form? Inside the admin? If you are using it on a custom page, maybe you forgot to print out the error message for your phone_number field? I just checked my code of a nearly identical use case and i cant spot a flaw in your code, but please post how you are using the form. – Andy Aug 27 '18 at 07:57
  • I’m the same as Andy - all looks good to me. Try simply using {{ form }} inside the
    tag to see if the error works then...
    –  Aug 27 '18 at 08:31
  • Andy, thanks for the suggestion. The problem was that in my template I did not print the error indeed, I checked this post https://stackoverflow.com/questions/14647723/django-forms-if-not-valid-show-form-with-error-message and understood how it is supposed to work. But since in my case the form submit was via Ajax and the response from the view was via JsonResponse, I did not get anything. I added the error text into the JsonResponse. It will do for now. Thanks again! – Victor Di Aug 28 '18 at 05:07

1 Answers1

0

RegexValidator(regex=regex, message=(message),) create a like that include message in ()

Rivak Shah
  • 29
  • 6