5

I have a RegexValidator for a telephone field. It works to return the error when I render the form again. However, I noticed the "Please fill out this field" error message when trying to submit the form with a blank input, which doesn't re-render the form to show the message. How can I use this type of message for my own validator?

Models.py

class Proveedor(models.Model):
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 code='invalid_phone_number',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    telefono = models.CharField(max_length=15, validators=[phone_regex], verbose_name='Teléfono')
    telefono_de_representante = models.CharField(max_length=15,
                                                 validators=[phone_regex],
                                                 verbose_name='Teléfono de representante')
    ...

Forms.py - I thought the error_messages part was a potential solution but it didn't change anything

class ProveedorForm(BaseModelForm):
    class Meta:
        model = Proveedor
        fields = ('nombre', 'telefono', 'representante', 'telefono_de_representante', 'correo_electronico')

    def __init__(self, *args, **kwargs):
        super(ProveedorForm, self).__init__(*args, **kwargs)
        self.fields['telefono'].error_messages = {'invalid_phone_number': 'Phone number must be entered in the format: \'+999999999\'. Up to 15 digits allowed.'}

Views.py - I can access the errors from the last render statement (if form not valid) but this requires the page to be rendered again

def proveedores(request, error=None):
    if request.method == "POST":
        form = ProveedorForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('menu:proveedores')
        return render(request, 'menu/proveedores.html', {'form': form})

How can I make this type of message for my phone number validator?

enter image description here

Thanks for the help!

EDIT

After reading Guillermo's response, I realized the 'required' error message wasn't connected to the model validators. Is there a way to connect the model validators to the front end error messages so that the user doesn't have to submit the form to receive the message?

1
  • 1
    the "please fill out this field" is an HTML message you can display if you write "required" in the input element attributes. It's not a feature in Django it's how HTML works. Commented Sep 20, 2022 at 0:32

5 Answers 5

4

As you didn't configure the field with

blank= True

https://docs.djangoproject.com/es/2.1/ref/models/fields/#blank

it is a required field, therefore it is rendered in the template as that, so the browser ask it to be filled.

You have to add the attribute:

telefono = models.CharField(
    max_length=15, 
    validators=[phone_regex], 
    verbose_name='Teléfono',
    blank=True
)

Also you could, instead of create a field for regex, create a library with a function, so you could reuse it on other models.

EDIT:

Validators are not meant to be in the model definition, as it is a representation of a table, and a regex field is not a field of a table.

You could create a folder with an __init__.py so it can be called from your apps

root_folder/
    myapp/
    myvalidators/
       __init__.py
       myvalidators.py

In the myvalidators.py you create functions or constant with the validations you need:

myvalidators.py

REGEX_PATTERN_PHONE = your_regex
MSG_PHONE_NOT_VALID = your_message

In your models then add the validation pattern with RegexValidator

from myvalidators import myvalidators

...  
telefono = models.CharField(
    max_length=15, 
    validators=[phone_regex], 
    verbose_name='Teléfono',
    blank=True,
    validators = [RegexValidator(myvalidators.REGEX_PATTERN_PHONE, myvalidators.MSG_PHONE_NOT_VALID)],
)
...

With this approach you can reuse the regex on any app or project, and in different fields that have to be validated the same way.

5
  • Hi Guillermo, thanks for the answer. I actually like that it has that error message because that field should be required, and want a similar error message to show also when I put in an invalid phone number. What do you mean create a library with a function? The error message was built in to the Django form view but I'm not sure how to access it for my RegexValidator.
    – CCCodes
    Commented Aug 15, 2018 at 16:16
  • My question was not how to reuse a validator, but I was actually wondering how to get the warning as shown in the screenshot. Putting the validator in another file seems to only change the structure of the code.
    – CCCodes
    Commented Aug 15, 2018 at 18:36
  • @CCCodes Maybe I misunderstood your question. The warning is issued by the browser because the field has the required attribute. It will be rendered that way in all the fields that are required, and for more details, it will be different on each browser, even the language. To change the behaviour, you would have to render the field without the required attribute, and then your custom validator message will appear. You also can achieve this via javascript, so you don't have to send the form, which I think is better on the client part, but always having the server validation. Commented Aug 15, 2018 at 19:03
  • That makes sense. Is there any way to connect the front end validators to the model validators?
    – CCCodes
    Commented Aug 16, 2018 at 14:53
  • @CCCodes I'm not sure what you mean by that. You can't tie the validation in the client with the one in the server. Let's say that client validation, javascript and some html attributes, is "fake". What it it does is preventing wrong data to be sent to the server, but nothing more. The server has always got to perform it's own "real" validation: javascript could fail, or even be completely absent if deactivated in the browser. What you can do, is "mirroring" both validations, and more especifically, the client's must be a mirror of the server's. Commented Aug 17, 2018 at 17:31
1

This is probably HTML issue with browsers. Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields? You can remove this "required" just from html easy in a Django view also

form = NameForm(request.POST or None, use_required_attribute=False)

After this you will be able to use your validators

0

To actually solve your error replace your Proveedor class with

class Proveedor(models.Model):
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 code='invalid_phone_number',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    telefono = models.CharField(max_length=15, validators=[phone_regex], verbose_name='Teléfono', blank=true)
    telefono_de_representante = models.CharField(max_length=15,
                                                 validators=[phone_regex],
                                                 verbose_name='Teléfono de representante')
0

Django has a special package called phone field for entering phone numbers. To install you can use.
pip install django-phone-field
Then add 'phone_field' to your INSTALLED_APPS setting.

and configure it like

from phone_field import PhoneField

class Proveedor(models.Model):
telefono_de_representante = PhoneField(blank=True,verbose_name='Teléfono de representante')                                              
0

Just use this:

    telephone = forms.CharField(label='Teléfono:', max_length=20,
                                widget=forms.TextInput(attrs={'pattern': '[+0-9]{9,20}',
                                                             'placeholder': '666666666',
                                                             'title': 'Only numbers and plus sign'}))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.