作业25——完成注册功能
- js文件: onclick函数return True时才提交表单,return False时不提交表单。
-
function fnRegist() { var zcoUname = document.getElementById("zcuname") var zcoError = document.getElementById("zcerror_box") var zcoUword1 = document.getElementById("zcuword1") var zcoUword2 = document.getElementById("zcuword2") zcoError.innerHTML = "<br>" if (zcoUname.value.length < 6 || zcoUname.value.length > 12) { zcoError.innerHTML = "用户名为6到12位"; return false } else if ((zcoUname.value.charCodeAt(0) >= 48) && (zcoUname.value.charCodeAt(0) <= 57)) { zcoError.innerHTML = "用户名首位不能是数字"; return false } else for (var i = 0; i < zcoUname.value.length; i++) { if ((zcoUname.value.charCodeAt(i) < 48) || (zcoUname.value.charCodeAt(i) > 57) && (zcoUname.value.charCodeAt(i) < 97) || (zcoUname.value.charCodeAt(i) > 122)) { zcoError.innerHTML = "用户名只能是字母与数字"; return false } } if ((zcoUword1.value.length < 6) || (zcoUword1.value.length > 20)) { zcoError.innerHTML = "密码为6到20位"; return false } else if (zcoUword2.value.length == 0) { zcoError.innerHTML = "请再次输入密码"; return false } else if (zcoUword1 != zcoUword2) { document.getElementById("error_box").innerHTML = "两次密码不一致" return false; } return true }
- html文件:
- <form>中设置 action和method="post"
- <input> 中设置 name
-
<div class="zcbox"> <h2 class="zhuce">注册</h2> <form action="{{ url_for('regist') }}" method="post"> <div class="zcinput_box"> <input id="zcuname" type="text" placeholder="请输入用户名" name="username"> </div> <div class="zcinput_box"> <input id="zcunickname" type="text" placeholder="请输入昵称" name="nickname"> </div> <div class="zcinput_box"> <input id="zcuword1" type="password" placeholder="请输入密码" name="password"> </div> <div class="zcinput_box"> <input id="zcuword2" type="password" placeholder="请再次输入密码"> </div> <div id="zcerror_box"><br></div> <div class="zcinput_box"> <button onclick="fnRegist()">立即注册</button> </div> </form> </div>
- 主py文件中:
- from flask import request, redirect, url_for
- @app.route('/regist/', methods=['GET', 'POST’])
-
@app.route('/regist/',methods=['GET','POST']) def regist(): if request.method=='GET': return render_template('regist.html') else: # 获取form中的数据,判断用户名是否存在,存到数据库中 username=request.form.get('username') nickname = request.form.get('nickname') password=request.form.get('password') user=User.query.filter(User.username==username).first() # 重定向到登录页 if user: return u'用户名已存在' else: user=User(username=username,nickname=nickname,password=password) db.session.add(user) db.session.commit() return redirect(url_for('login'))
def regist():
if request.method == 'GET':
return render_template('regist.html')
else:
username = request.form.get(‘username’)#获取form中的数据
判断用户名是否存在
存到数据库中
redirect重定向到登录页