自定义表单字段验证
表单验证步骤
1.字段的to_python():数据转换
2.字段的validate():特异性验证
3.字段的run_validators():validators验证
4.字段clean():按顺序调用前3个
5.表单的clean_fieldname():自定义的验证
6.表单的clean():表单多个字段的验证
自定义字段:标签字段
class MultiTagFeild(forms.Field):
def __init__(self, max_length=None, tag_max_length=None, strip=True, *args, **kwargs):
self.max_length = max_length
self.tag_max_length = tag_max_length
self.strip = strip
super(MultiTagFeild, self).__init__(*args, **kwargs)
if max_length is not None:
self.validators.append(validators.MaxLengthValidator(int(max_length)))
def to_python(self, value):
if not value:
return []
value = value.split(',')
if self.strip:
value = [smart_text(x.strip()) for x in value if x.strip()]
return value
def validate(self, value):
super(MultiTagFeild, self).validate(value)
for tag in value:
validators.MaxLengthValidator(self.tag_max_length, "标签长度超限")(tag)
- 继承forms.Field类,实现to_python方法
- validate()相关验证
- validators验证器
def forbidden_tags_validator(value):
forbidden_tags = ['you', 'are', 'a', 'sb']
for tag in value:
if tag.lower() in forbidden_tags:
raise ValidationError('you are a sb.')
class InvalidTagValidator(object):
def __init__(self, message=None):
if message:
self.message = message
def __call__(self, value):
for tag in value:
if '@' in tag or '+' in tag or '-' in tag:
raise ValidationError('Enter a valid tag.')
- clean_name()验证和clean()验证
# form类的方法
class CustomForm(forms.Form):
name = forms.CharField(max_length=100)
tags = MultiTagFeild()
def __init__(self, *args, **kwargs):
super(CustomForm, self).__init__(*args, **kwargs)
self.fields['tags'].validators.append(forbidden_tags_validator)
self.fields['tags'].validators.append(InvalidTagValidator)
def clean_name(self):
value = self.cleaned_data.get('name')
if value == "admin":
raise ValidationError('%s已存在' % value)
return value
def clean(self):
super(CustomForm, self).clean()
name = self.cleaned_data.get('name')
tags = self.cleaned_data.get('tags')
if not tags or len(tags) <= 1:
self._errors['tags'] = self.error_class(['标签太少'])
if name == "help":
self.add_error("name", "帮助信息")
return self.cleaned_data