views.py
from django.shortcuts import render, HttpResponse
from django import forms
import json
import re
from django.core.exceptions import ValidationError
# Create your views here.
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('手机号码格式错误')
class InputForm(forms.Form):
# 下面使用的变量名必须和html中input标签的name值相同
# forms 的字段类型包括:IntegerField,CharField,URLField,EmailField,DateField等,但是没有手机号
# required=True表示对输入做验证
# error_messages 自定制提示信息
username = forms.CharField(required=True, error_messages={'required':'用户名不能为空'})
password = forms.CharField(required=True,
min_length=6,
max_length=10,
error_messages={'required':'密码不能为空','min_length':'至少6位',
'max_length':'至多10位'}
)
num = forms.IntegerField(error_messages={'required':'不能为空', 'invalid':'必须是数字'})
# 自定制验证方法关键就是参数validators,和自己的函数关联起来
phone = forms.CharField(validators=[mobile_validate,],)
def login(request):
if request.POST:
objPost = InputForm(request.POST)
ret = objPost.is_valid()
if ret:
print(objPost.clean())
# else:
# # from django.forms.utils import ErrorDict
# print(type(objPost.errors),objPost.errors.as_json())
return render(request, 'login.html', {'data': objPost})
else:
objGet = InputForm()
return render(request, 'login.html',{'data': objGet})
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.error-msg{
color:red;
}
</style>
</head>
<body>
<form action="/login/" method="POST">
<div>
<div>
{{ data.username }}
{% if data.errors.username %}
<span class="error-msg">{{ data.errors.username.0 }}</span>
{% endif %}
</div>
<div>
{{ data.password }}
{% if data.errors.password %}
<span class="error-msg">{{ data.errors.password.0 }}</span>
{% endif %}
</div>
<div>
{{ data.num }}
{% if data.errors.num %}
<span class="error-msg">{{ data.errors.num.0 }}</span>
{% endif %}
</div>
<div>
{{ data.phone }}
{% if data.errors.phone %}
<span class="error-msg">{{ data.errors.phone.0 }}</span>
{% endif %}
</div>
<input type="submit" value="提交" />
</div>
</form>
</body>
</html>
效果图:
上面这个图的提示应该是django 1.10 版本 新增