五十四:WTForms表单验证之自定义表单验证器
如果想要对表单中的某个字段进行自定义验证,则需要对这个字段进行单独的验证
1、定义一个方法,命名规则为:validate_字段名(self, filed)
2、在方法中,使用filed.data获取字段的值
3、如果验证成功,则不需要做任何操作,如果验证失败,则需要抛出一个异常:wtforms.validators.ValidationError(异常信息)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="#" method="post">
<table>
<tbody>
<tr>
<td>验证码:</td>
<td><input type="text" name="captcha"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="点击提交"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
from wtforms import Form, StringField
from wtforms.validators import Length, ValidationError
class RegistForm(Form):
captcha = StringField(validators=[Length(4, 4, message='验证码为4位')])
def validate_captcha(self, filed): # 自定义验证器:validate_字段名
print(filed.data)
print(type(filed))
if filed.data != '1234':
raise ValidationError('验证码错误') # 验证不通过时抛出异常
from flask import Flask, request, render_template
from forms import RegistForm
app = Flask(__name__)
@app.route('/regist/', methods=['GET', 'POST'])
def regist():
form = RegistForm(request.form)
if request.method == 'POST':
if form.validate():
return '验证通过'
else:
print(form.errors)
return form.errors
return render_template('validate.html')
if __name__ == '__main__':
app.run(debug=True)
讨论群:249728408