我希望在使用flask提交之前使用javaScript DOM验证输入表单。代码如下所示:
<form role="search" class="navbar-form nav-item" action="s" method="GET">
<input
type="text"
id="search"
placeholder="Search Course"
class="form-control"
name="search_string"
value="{{ search_value }}"
/>
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>
@main.route("/s", methods=['GET', 'POST'])
def search():
page = request.args.get('page', 1, type=int)
if request.method == 'GET' and 'search_string' in request.args:
search_value = request.args.get('search_string')
#clear session if no search
if search_value=="":
session.clear()
session['search'] = search_value
search = "%{}%".format(session['search'])
#save keyword in database
saved_search = Keywords.query.filter_by(keyword = session['search']).count() # search if exist in database before saving
if saved_search < 1:
save_search = Keywords(keyword=session['search'])
db.session.add(save_search)
db.session.commit()
#end save keyword in database
posts1 = Post.query.filter(Post.course_name.like(search)).count()
posts = Post.query.filter(Post.course_name.like(search)).order_by(Post.timestamp.desc()).paginate(page=page, per_page=10)
if posts1 > 0 and len(search_value)>0:
flash('Search result for {}'.format(search_value), 'success')
return render_template('search.html', posts=posts, search_value = search_value)
else:
flash('No search result found for {}'.format(search_value), 'danger')
return redirect(url_for('main.index'))
else:
posts = Post.query.filter(Post.course_name.like("%{}%".format(session['search']))).order_by(Post.timestamp.desc()).paginate(page=page, per_page=10)
return render_template('search.html', posts=posts)
现在我该如何编写JavaScript代码,以确保在运行Flask代码之前,已在javascript中验证了输入字段(search):def search():
答案 0 :(得分:1)
好的,所以您肯定要进行一些表单验证。首先,它将包括在某种事件类型上触发的某种类型的字符串格式。
我已经使用Vanilla JS编写了一个简单的表单验证Web应用程序,该应用程序执行DOM中反映的表单验证,您可以克隆该存储库,并在自己的计算机上查看它的运行状况,并使用它,但是它应该涵盖您所需要的内容需要。