fromWtformsImportForm,stringfield,integerfield fromWtformsImportvalidators fromWtforms.validatorsImportLength,equalto,email,inputrequired,numberrange, Regexp,url,uuidclassRegisterform (Form): Username= Stringfield (Validators=[length (max=10,min=3,message='Incorrect user name length')]) password= Stringfield (Validators=[length (max=10,min=3,message='password length is incorrect')]) password_repeat= Stringfield (Validators=[length (max=10,min=3,message='password length is incorrect'), Equalto ('Password')])classLoginForm (Form):#email = Stringfield (Validators=[email (message= ' mailbox format is incorrect ')]) #username = Stringfield (validators=[inputrequired (message= ' must fill in username ')]) #inputrequired必填字段 #Age = Integerfield (Validators=[numberrange (12,100))) #验证数字在某某区间之内 #phone = Stringfield (Validators=[regexp (R ' 1[85347]\d{9} ', message= ' phone number format incorrect ')]) #home_page = Stringfield (Validators=[url ())) #必须验证必须是一个跳转链接UUID = Stringfield (Validators=[uuid ()))#Verify that the UUID
fromFlaskImportflask,request,render_template fromFormsImportRegisterform,loginformapp= Flask (__name__) @app. Route ('/')defHello_world ():return 'Hello world!'@app. Route ('/register/', methods=['Get','Post'])defRegister ():ifRequest.method = ='GET': returnRender_template ('register.html') Else: #username = request.form.get (' username ') #password = request.form.get (' password ') #password_repeat = request.form.get (' password_repeat ') #if 3 > Len (username) or len (username) >: #return ' user name length is incorrect ' #if 3 > Len (password) or len (password) >: #return ' password length is incorrect ' #if password! = password_repeat: #return ' password input inconsistent 'form =registerform (Request.Form)ifform.validate ():return 'Success' Else: Print(form.errors)#{' username ': [' incorrect length of user name '], #' password ': [' password length is incorrect '], ' password_repeat ': [' password length is incorrect ']} #because it's a dictionary, I don't write it. return 'fail'@app. Route ('/login/', methods=['Get','Post'])#If the methods does not have a post method, the status code 405 error is reported,#static file does not allow the Post method to be requesteddeflogin ():ifRequest.method = ="GET": returnRender_template ('login.html') Else: Login_form=loginform (Request.Form)iflogin_form.validate ():return 'Success' Else: return '{Errors}'. Format (Errors=login_form.errors.get ('Phone') [0])#Get specific error messagesif __name__=='__main__': App.run (Debug=true)
Wtforms commonly used validators