[Solved]-Django: Checking CharField format in form with a regular expression

23πŸ‘

βœ…

First you need a regex validator:
Django validators / regex validator

Then, add it into the validator list of your field:
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]
    )
πŸ‘€Art

1πŸ‘

you could also ask from both part in your form, it 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 join them in your view :

capa = self.cleaned_data.get('capa1', None) + '-' + self.cleaned_data.get('capa2', None)
πŸ‘€romainm

1πŸ‘

You can also use RegexField. It’s the same as CharField but with additional argument regex. Under the hood it uses validators.

Example:

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

1πŸ‘

Regex validator does not work for me in Django 2.2

Step to set up custom validation for a field value:

  1. define the validation function:

    def number_code_validator(value):
        if not re.compile(r'^\d{10}$').match(value):
            raise ValidationError('Enter Number Correctly')
    
  2. In the form add the defined function to validators array of the field:

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

Leave a comment