Django: validating CharField format in regex form

class CapaForm(forms.Form):
    capa = forms.CharField(required=False)

      

When submitting the form, I want to check the format of the field capa

. I want the user to correctly enter the capa format as 6 digits, a dash and two numbers. (###### - ##)

def search(self):
    capa = self.cleaned_data.get('capa', None)

    if ("\d{6}\-\d{2}" or None) not in capa:
            raise forms.ValidationError("CAPA format needs to be ######-##!")

      

This currently prevents me from submitting a properly formatted capa and throws a ValidationError. I think the problem is that I am trying to compare regex to object. How can I check the "capa" format the user is trying to send?

********* UPDATE

Everything works now EXCEPT when I enter the wrong format in the CAPA field. I get an error The view incidents.views.index didn't return an HttpResponse object. It returned None instead.

Is this related to the changes I made?

from django.core.validators import RegexValidator
my_validator = RegexValidator("\d{6}\-\d{2}", "CAPA format needs to be ######-##.")

class CapaForm(forms.Form):
    capa = forms.CharField(
        label="CAPA",
        required=False, # Note: validators are not run against empty fields
        validators=[my_validator]
        )

def search(self):
    capa = self.cleaned_data.get('capa', None)
    query = Incident.objects.all()
    if capa is not '':
            query = query.filter(capa=capa)
    return(query)

      

+5


source to share


4 answers


First you need a regex validator : Django Validators / Regex Validator

Then add it to your field's validator list: using validators in forms



Simple example below:

from django.core.validators import RegexValidator
my_validator = RegexValidator(r"A", "Your string should contain letter A in it.")

class MyForm(forms.Form):

    subject = forms.CharField(
        label="Test field",
        required=True,  # Note: validators are not run against empty fields
        validators=[my_validator]
    )

      

+12


source


you can also request both parts in your form, this would be cleaner for the user:

class CapaForm(forms.Form):
capa1 = forms.IntegerField(max_value=9999, required=False)
capa2 = forms.IntegerField(max_value=99, required=False)

      



and then just attach them to your view:

capa = self.cleaned_data.get('capa1', None) + '-' + self.cleaned_data.get('capa2', None)

      

+1


source


You can also use RegexField . This is the same as CharField

but with an additional argument regex

. Validators are used under the hood .

Example:

class MyForm(forms.Form):
    field1 = forms.RegexField(regex=re.compile(r'\d{6}\-\d{2}'))

      

0


source


Regex validator not working for me in Django 2.4

Step to set up custom validation of field value:

  1. define a check function:

    def number_code_validator (value): if not re.compile (r '^ \ d {10} $'). match (value): raise a ValidationError ('Enter the number correctly')

  2. In the form, add a specific function to the field validator array:

    number = forms.CharField (label = "Number", widget = TextInput (attrs = {'type': 'number'}), validators = [number_code_validator])

hope this helps

0


source







All Articles