@H_403_3@
class CapaForm(forms.Form): capa = forms.CharField(required=False)
提交表单后,我想检查capa字段的格式.我想要求用户正确输入capa格式为6个数字,短划线和两个数字. (###### – ##)
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 ######-##!")
它目前不允许我提交格式正确的capa并抛出ValidationError.我认为问题是我正在尝试将正则表达式与对象进行比较.如何检查用户尝试提交的’capa’的格式?
********* UPDATE
当我在CAPA字段中输入错误的格式时,现在一切正常.我收到错误视图incidents.views.index没有返回HttpResponse对象.它返回了None.这与我所做的改变有关吗?
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)
解决方法
首先,您需要一个正则表达式验证器:
Django validators / regex validator
Django validators / regex validator
然后,将其添加到您的字段的验证器列表中:
using validators in forms
简单示例如下:
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] )
@H_403_3@