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?
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?