方式一:RegexValidator对象 from django.core.validators import RegexValidator phone = fields.CharField(
validators=[RegexValidator(r‘^[0-9]+$‘, ‘请输入数字‘), RegexValidator(r‘^159[0-9]+$‘, ‘数字必须以159开头‘)]) # 自定义验证规则进行验证 方式二:函数
from django.core.exceptions import ValidationError
def mobile_validate(value): mobile_re = re.compile(r‘^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$‘) if not mobile_re.match(value): raise ValidationError(‘手机号码格式错误‘)
phone = fields.CharField( validators=[mobile_validate,]) # 自定义验证规则进行验证 方式三:钩子函数1,分析
通过上面分析1,通过_clean_fields实现
def _clean_fields(self): for name, field in self.fields.items(): # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. if field.disabled: value = self.get_initial_for_field(field, name) else: value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) try: if isinstance(field, FileField): initial = self.get_initial_for_field(field, name) value = field.clean(value, initial) else: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, ‘clean_%s‘ % name): value = getattr(self, ‘clean_%s‘ % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e) 通过上面可以实现
def clean_phone(self): # 去取用户提交的值:可能是错误的,可能是正确 value = self.cleaned_data[‘phone‘] mobile_re = re.compile(r‘^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$‘) if not mobile_re.match(value): raise ValidationError(‘手机号码格式错误‘) if models.UserInfo.objects.filter(phone=value).count(): raise ValidationError(‘手机号码已经存在‘) return value
注意钩子字段只能取自己的。不然可能取不到。源码是通过__dict__取得
执行流程 1,正则表达式 2,clean钩子函数
时间: 2024-11-12 15:36:58