- js文件: onclick函数return True时才提交表单,return False时不提交表单。
function foLogin() { var oUname = document.getElementById("uname"); var oError = document.getElementById("error_box"); var oUpass = document.getElementById("upass"); var oUpass1=document.getElementById("upass1"); var isoError = true; oError.innerHTML = "<br>"; if (oUname.value.length < 6 || oUname.value.length > 20) { oError.innerHTML = "用户名要6-20位"; isoError = false; return isoError; }else if((oUname.value.charCodeAt(0)<=48)&&(oUname.value.charCodeAt(0)>=57)){ oError.innerHTML="首字母不能为数字"; isoError = false; return isoError; }else for(var i=0;i<oUname.value.length;i++){ if((oUname.value.charCodeAt(i)<48||oUname.value.charCodeAt(i)>57)&&(oUname.value.charCodeAt(i)<97||oUname.value.charCodeAt(i)>122)){ oError.innerHTML="只能包含字母和数字"; isoError = false; return isoError; } } if (oUpass.value.length < 6 || oUpass.value.length > 20){ oError.innerHTML = "密码要6-20位"; isoError = false; return isoError; } if(oUpass.value()!=oUpass1.value()){ oError.innerHTML="两次密码不一致"; isoError = false; return isoError; } window.alert("注册成功!!") return true; }
html文件:
- <form>中设置 action和method="post"
- <input> 中设置 name
<form action="{{ url_for('zhuce') }}" method="post"> <div class="input_box"> 用户名: <input id="uname" type="text" placeholder="请输入用户名" name="username"> {# 昵称:<input id="unickname" type="text" placeholder="昵称" name="nickname">#} </div> <div class="input_box"> 密码: <input id="upass" type="password" placeholder="请输入密码" name="password"> </div> <div class="input_box "> 密码:<input id="upass1" type="password" placeholder="请再次输入密码"> </div> <div id="error_box"><br></div> <div class="input_box"> <button onclick="foLogin()">注册</button> </div> </form>
- 主py文件中:
- from flask import request, redirect, url_for
- @app.route('/regist/', methods=['GET', 'POST’])
def regist():
if request.method == 'GET':
return render_template('regist.html')
else:
username = request.form.get(‘username’)#获取form中的数据
判断用户名是否存在
存到数据库中
redirect重定向到登录页
@app.route('/zhuce',methods=['GET','POST']) def zhuce(): if request.method=='GET': return render_template('zhuce.html') else: username=request.form.get('username') password=request.form.get('password') # nickname=request.form.get('nickname') user=User.query.filter(User.username==username).first() if user: return 'username existed' else: user=User(username=username,password=password) db.session.add(user) db.session.commit() return redirect(url_for('denglu'))
- 主py文件中: