modelform 还有个功能叫clean,可以检查用户输入的数据。用法如下
from django import forms
from operation.models import UserAsk
import re
class UserAskForm(forms.ModelForm):
class Meta:
model = UserAsk
fields = ['name','mobile','course_name']
def clean_mobile(self):
"""
验证手机号码是否合法
"""
mobile = self.cleaned_data['mobile']
REGEX_MOBILE = "^1[358]\d{9}$|^147\d{8}$|^176\d{8}$"
p = re.compile(REGEX_MOBILE)
if p.match(mobile):
return mobile
else:
raise forms.ValidationError("手机号码非法",code="mobile_invalid")
在类下定义clean_XXX方法,必须以clean开头,XXX是字段。import re 引入正则表达式。这样写完点击前端提交,如果有问题就会显示添加出错了~
网友评论