Reputation: 1006
class CapaForm(forms.Form):
capa = forms.CharField(required=False)
Upon form submission I want to check the format of the capa
field. I want to require the user to enter the capa format correctly as 6 numbers, 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 ######-##!")
It's currently not letting me submit a correctly formatted capa and throws the ValidationError. I think the problem is I'm trying to compare a regular expression to an object. How can I check the format of the 'capa' the user tries to submit?
*********UPDATE
Everything is working now EXCEPT when I type the wrong format in the CAPA field. I get the 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)
Upvotes: 13
Views: 16860
Reputation: 361
Regex validator does not work for me in Django 2.2
Step to set up custom validation for a field value:
define the validation function:
def number_code_validator(value):
if not re.compile(r'^\d{10}$').match(value):
raise ValidationError('Enter Number Correctly')
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])
Upvotes: 1
Reputation: 2335
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]
)
Upvotes: 25
Reputation: 1129
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}'))
Upvotes: 1
Reputation: 281
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)
Upvotes: 1