后端
from django import forms
class myForms(forms.Form):
username = forms.CharField(
min_length=6, # 最少6个字符
max_length=20, # 最多20个字符
label="用户名:", # label标签名
error_messages={ # 定义错误提示信息(默认英文)
"min_length": '用户名不能小于6位',
"max_length": '用户名不能超过20位',
"required": '用户名不能为空',
},
required: False, # 用户名可以为空
initial="请输入用户名", # 设置初始值
widget=forms.widgets.TextInput( # 设置标签类型
attrs={ # 设置标签属性
"class": "form-control" # 设置class属性
}
)
)
password = forms.CharField(
min_length=6, # 最少6个字符
max_length=20, # 最多20个字符
label="密码:", # label标签名
error_messages={ # 定义错误提示信息(默认英文)
"min_length": '密码不能小于6位',
"max_length": '密码不能超过20位',
"required": '密码不能为空',
},
widget=forms.widgets.TextInput( # 设置标签类型
attrs={ # 设置标签属性
"class": "form-control", # 设置class属性
"placeholder": "请输入密码"
}
)
)
# 局部钩子
def clean_username(self):
username = self.cleaned_data.get("username")
if "金*梅" in username:
self.add_error("username", "用户名中包含违规信息!") # 添加错误信息到error里
return username
# 全局钩子
def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if password in username:
self.add_error("password", "用户名中不能包含密码") # 添加错误信息到error里
return self.cleaned_data
def test_form(request):
my = myForms()
if request.method == "POST":
my = myForms(request.POST)
if my.is_valid():
return HttpResponse("数据校验成功!")
return render(request, 'test_form.html', locals())
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load static %}
<script src="{% static 'js/jquery-3.4.1.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/sweetalert.css' %}">
<script src="{% static 'js/sweetalert.min.js' %}"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form method="post" novalidate class="form">
{% for foo in my1 %}
<div class="form-group">
<label for="{{ foo.id_for_label }}">{{ foo.label }}</label>
{{ foo }}
<span style="color: red">{{ foo.errors.0 }}</span>
</div>
{% endfor %}
<input class="btn btn-primary" type="submit" value="提交">
</form>
</div>
</div>
</div>
</body>
</html>