DIV CSS 佈局教程網

表單提交前驗證的三種 JS 寫法對比
編輯:JavaScript綜合知識     

把基本驗證放在前端,能即時給使用者回饋、也減輕後端負擔。本文以 Django 專案為背景,示範三種常見的攔截方式並分析差異。

方法一:監聽 submit 事件

用 jQuery 的 bind("submit", ...) 攔截表單,驗證失敗就 return false 阻止送出。這是三者中最乾淨的做法——驗證邏輯與 HTML 分離,且按下 Enter 送出時同樣會被攔下。

<script type="text/javascript">
function jump()
{
 document.getElementById("firstname").value=""
 document.getElementById("lastname").value=""
 $("#firstnameLabel").text("")
 $("#lastnameLabel").text("")
}
$(document).ready(function(){
 $("#form1").bind("submit", function(){
  var txt_firstname = $.trim($("#firstname").attr("value"))
  var txt_lastname = $.trim($("#lastname").attr("value"))
  $("#firstnameLabel").text("")
  $("#lastnameLabel").text("")
  var isSuccess = 1;
  if(txt_firstname.length == 0)
  {
   $("#firstnameLabel").text("firstname不能為空!")
   $("#firstnameLabel").css({"color":"red"});
   isSuccess = 0;
  }
  if(txt_lastname.length == 0)
  {
   $("#lastnameLabel").text("lastname不能為空!")
   $("#lastnameLabel").css({"color":"red"});
   isSuccess = 0;
  }
  if(isSuccess == 0)
  {
   return false;
  }
 })
})
</script>

方法二:onsubmit 屬性回傳布林值

把驗證寫成獨立函式,透過表單的 onsubmit="return check()" 呼叫。邏輯與方法一相同,只是掛載位置換到 HTML 屬性上。

<form id="form1" method="post" action="/DealWithForm1/" onsubmit="return check()">

缺點是 HTML 與 JS 混在一起,欄位一多維護不易;優點是不依賴 jQuery,程式碼位置一目了然。

方法三:把提交按鈕改成一般按鈕

最直白的做法:按鈕改成 type="button",驗證通過後才用 JS 呼叫 form1.submit()。

<button type="button" onclick="checktosubmit()">提交</button>

這個做法有個明顯缺點:使用者在輸入框按 Enter 不會送出,因為已經沒有 submit 按鈕了。對習慣鍵盤操作的使用者是一大退步。

後端視圖(Django)

views.py
#coding: utf-8
from django.http import HttpResponse
from django.shortcuts import render_to_response
def DealWithForm1(request):
 if request.method=="POST":
  FirstName=request.POST.get('firstname','')
  LastName=request.POST.get('lastname','')
  if FirstName and LastName:
   return HttpResponse("<html><body>"+FirstName+" "+LastName+u"! 你提交了表單!</body></html>")
  else:
   return HttpResponse('<html><script>alert("firstname或lastname不能為空!");window.location="/DealWithForm1"</script></html>')
 else:
  return render_to_response('formpage1.html')

urls.py
from django.conf.urls.defaults import patterns, url
import views
urlpatterns = patterns('',
  url(r'^Resource/(?P<path>.*)$','django.views.static.serve'),
  url(r'^DealWithForm1','views.DealWithForm1'),
)

該選哪一個?

方法一(監聽 submit)是最佳選擇:保留 Enter 送出、邏輯集中、易於擴充。方法二可用但風格偏舊;方法三除非有特殊需求,不建議採用。

幾個必須修正的問題

一、後端那段程式有 XSS 漏洞。把 FirstName、LastName 直接拼進 HTML 輸出,使用者輸入 <script> 就會執行。請改用模板自動轉義,或至少 django.utils.html.escape()。同理,前端用 .text() 而非 .html() 是正確的,值得保持。

二、前端驗證永遠不能取代後端驗證。使用者關掉 JS、直接改寫 POST 就能繞過。後端一定要再驗一次,最好用 Django Forms 或 DRF Serializer 統一處理。

三、错误提示要連到欄位。用 <label for="firstname"> 關聯,並在出錯時設定 aria-invalid="true" 與 aria-describedby,螢幕閱讀器才能把「哪裡錯、錯在哪」唸出來。只用紅字呈現,色覺障礙使用者看不出差別。

四、API 更新。render_to_response 已從 Django 移除,django.conf.urls.defaults 也早已不存在。新專案請用 render() 與 path()/re_path(),靜態檔案交由 settings.STATIC_URL 處理而非手動配置路由。CSRF 中間件也務必啟用並在表單中放入 {% csrf_token %}。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved