在表单提交前进行验证的几种方式


转载自:http://blog.csdn.net/qian_f/article/details/9631691

===============================================================


在Django中,为了减轻后台压力,可以利用JavaScript在表单提交前对表单数据进行验证。下面提供了有效的几种方式(每个.html文件为一种方式)。

formpage1.html

[html]  view plain  copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>Example1</title>  
  6. <script type="text/javascript" src="/Resource/jquery-1.4.1.js"></script>  
  7.   
  8. <script type="text/javascript">  
  9. function jump()  
  10. {  
  11.     //清空表单所有数据  
  12.     document.getElementById("firstname").value=""  
  13.     document.getElementById("lastname").value=""  
  14.     $("#firstnameLabel").text("")  
  15.     $("#lastnameLabel").text("")  
  16. }  
  17.   
  18. $(document).ready(function(){  
  19.     $("#form1").bind("submit", function(){  
  20.         var txt_firstname = $.trim($("#firstname").attr("value"))  
  21.         var txt_lastname = $.trim($("#lastname").attr("value"))  
  22.           
  23.         $("#firstnameLabel").text("")  
  24.         $("#lastnameLabel").text("")  
  25.           
  26.         var isSuccess = 1;  
  27.         if(txt_firstname.length == 0)  
  28.         {  
  29.             $("#firstnameLabel").text("firstname不能为空!")  
  30.             $("#firstnameLabel").css({"color":"red"});  
  31.             isSuccess = 0;  
  32.         }  
  33.         if(txt_lastname.length == 0)  
  34.         {  
  35.             $("#lastnameLabel").text("lastname不能为空!")  
  36.             $("#lastnameLabel").css({"color":"red"});  
  37.             isSuccess = 0;  
  38.         }  
  39.         if(isSuccess == 0)  
  40.         {  
  41.             return false;  
  42.         }  
  43.         })  
  44.     })  
  45. </script>  
  46. </head>  
  47. <body>  
  48. 提交表单前进行验证(方法一)  
  49. <hr width="40%" align="left" />  
  50. <form id="form1" method="post" action="/DealWithForm1/">   
  51. <table>  
  52. <tr>  
  53. <td>first_name:</td>  
  54. <td><input name="firstname" type="text" id="firstname" /></td>  
  55. <td><label id="firstnameLabel"></label></td>  
  56. </tr>  
  57. <tr>  
  58. <td>last_name:</td>  
  59. <td><input name="lastname" type="text" id="lastname" /></td>  
  60. <td><label id="lastnameLabel"></label></td>  
  61. </tr>  
  62. </table>  
  63. <hr width="40%" align="left" />  
  64. <button type="submit">提交</button>  
  65. <button type="button" onclick="jump();">取消</button>  
  66. </form>  
  67. </body>  
  68. </html>  

formpage2.html

[html]  view plain  copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>Example2</title>  
  6. <script type="text/javascript" src="/Resource/jquery-1.4.1.js"></script>  
  7.   
  8. <script type="text/javascript">  
  9. function jump()  
  10. {  
  11.     //清空表单所有数据  
  12.     document.getElementById("firstname").value=""  
  13.     document.getElementById("lastname").value=""  
  14.     $("#firstnameLabel").text("")  
  15.     $("#lastnameLabel").text("")  
  16. }  
  17.   
  18. function check(){  
  19.     var txt_firstname = $.trim($("#firstname").attr("value"))  
  20.     var txt_lastname = $.trim($("#lastname").attr("value"))  
  21.       
  22.     $("#firstnameLabel").text("")  
  23.     $("#lastnameLabel").text("")  
  24.       
  25.     var isSuccess = 1;  
  26.     if(txt_firstname.length == 0)  
  27.     {  
  28.         $("#firstnameLabel").text("firstname不能为空!")  
  29.         $("#firstnameLabel").css({"color":"red"});  
  30.         isSuccess = 0;  
  31.     }  
  32.     if(txt_lastname.length == 0)  
  33.     {  
  34.         $("#lastnameLabel").text("lastname不能为空!")  
  35.         $("#lastnameLabel").css({"color":"red"});  
  36.         isSuccess = 0;  
  37.     }  
  38.     if(isSuccess == 0)  
  39.     {  
  40.         return false;  
  41.     }  
  42.     return true;  
  43.     }  
  44. </script>  
  45. </head>  
  46. <body>  
  47. 提交表单前进行验证(方法二)  
  48. <hr width="40%" align="left" />  
  49. <form id="form1" method="post" action="/DealWithForm1/" onsubmit="return check()">   
  50. <table>  
  51. <tr>  
  52. <td>first_name:</td>  
  53. <td><input name="firstname" type="text" id="firstname" /></td>  
  54. <td><label id="firstnameLabel"></label></td>  
  55. </tr>  
  56. <tr>  
  57. <td>last_name:</td>  
  58. <td><input name="lastname" type="text" id="lastname" /></td>  
  59. <td><label id="lastnameLabel"></label></td>  
  60. </tr>  
  61. </table>  
  62. <hr width="40%" align="left" />  
  63. <button type="submit">提交</button>  
  64. <button type="button" onclick="jump();">取消</button>  
  65. </form>  
  66. </body>  
  67. </html>  

formpage3.html

[html]  view plain  copy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>Example3</title>  
  6. <script type="text/javascript" src="/Resource/jquery-1.4.1.js"></script>  
  7.   
  8. <script type="text/javascript">  
  9. function jump()  
  10. {  
  11.     //清空表单所有数据  
  12.     document.getElementById("firstname").value=""  
  13.     document.getElementById("lastname").value=""  
  14.     $("#firstnameLabel").text("")  
  15.     $("#lastnameLabel").text("")  
  16. }  
  17.   
  18. function checktosubmit(){  
  19.     var txt_firstname = $.trim($("#firstname").attr("value"))  
  20.     var txt_lastname = $.trim($("#lastname").attr("value"))  
  21.       
  22.     $("#firstnameLabel").text("")  
  23.     $("#lastnameLabel").text("")  
  24.       
  25.     var isSuccess = 1;  
  26.     if(txt_firstname.length == 0)  
  27.     {  
  28.         $("#firstnameLabel").text("firstname不能为空!")  
  29.         $("#firstnameLabel").css({"color":"red"});  
  30.         isSuccess = 0;  
  31.     }  
  32.     if(txt_lastname.length == 0)  
  33.     {  
  34.         $("#lastnameLabel").text("lastname不能为空!")  
  35.         $("#lastnameLabel").css({"color":"red"});  
  36.         isSuccess = 0;  
  37.     }  
  38.     if(isSuccess == 1)  
  39.     {  
  40.         form1.submit();  
  41.     }  
  42. }  
  43. </script>  
  44. </head>  
  45. <body>  
  46. 提交表单前进行验证(方法三)  
  47. <hr width="40%" align="left" />  
  48. <form id="form1" method="post" action="/DealWithForm1/">   
  49. <table>  
  50. <tr>  
  51. <td>first_name:</td>  
  52. <td><input name="firstname" type="text" id="firstname" /></td>  
  53. <td><label id="firstnameLabel"></label></td>  
  54. </tr>  
  55. <tr>  
  56. <td>last_name:</td>  
  57. <td><input name="lastname" type="text" id="lastname" /></td>  
  58. <td><label id="lastnameLabel"></label></td>  
  59. </tr>  
  60. </table>  
  61. <hr width="40%" align="left" />  
  62. <button type="button" onclick="checktosubmit()">提交</button>  
  63. <button type="button" onclick="jump();">取消</button>  
  64. </form>  
  65. </body>  
  66. </html>  




以下是视图函数、URL配置以及相关设置



views.py

[python]  view plain  copy
  1. #coding: utf-8  
  2.   
  3. from django.http import HttpResponse  
  4. from django.shortcuts import render_to_response  
  5.   
  6. def DealWithForm1(request):  
  7.     if request.method=="POST":  
  8.         FirstName=request.POST.get('firstname','')  
  9.         LastName=request.POST.get('lastname','')  
  10.         if FirstName and LastName:  
  11.             response=HttpResponse()  
  12.             response.write("<html><body>"+FirstName+" "+LastName+u"! 你提交了表单!</body></html>")  
  13.             return response  
  14.           
  15.         else:  
  16.             response=HttpResponse()  
  17.             response.write('<html><script type="text/javascript">alert("firstname或lastname不能为空!");\  
  18. window.location="/DealWithForm1"</script></html>')  
  19.             return response  
  20.     else:  
  21.         return render_to_response('formpage1.html')  
  22.   
  23.   
  24. def DealWithForm2(request):  
  25.     if request.method=="POST":  
  26.         FirstName=request.POST.get('firstname','').encode("utf-8")  
  27.         LastName=request.POST.get('lastname','').encode("utf-8")  
  28.         if FirstName and LastName:  
  29.             html="<html><body>"+FirstName+" "+LastName+"! 你提交了表单!"+"</body></html>"  
  30.             return HttpResponse(html)  
  31.         else:  
  32.             response=HttpResponse()  
  33.             response.write('<html><script type="text/javascript">alert("firstname或lastname不能为空!");\  
  34. window.location="/DealWithForm2"</script></html>')  
  35.             return response  
  36.     else:  
  37.         return render_to_response('formpage2.html')  
  38.   
  39.   
  40. def DealWithForm3(request):  
  41.     if request.method=="POST":  
  42.         FirstName=request.POST.get('firstname','')  
  43.         LastName=request.POST.get('lastname','')  
  44.         if FirstName and LastName:  
  45.             response=HttpResponse()  
  46.             response.write('<html><body>'+FirstName+LastName+u'! 你提交了表单!</body></html>')  
  47.             return response  
  48.           
  49.         else:  
  50.             response=HttpResponse()  
  51.             response.write('<html><script type="text/javascript">alert("firstname或lastname不能为空!");\  
  52. window.location="/DealWithForm3"</script></html>')  
  53.             return response  
  54.     else:  
  55.         return render_to_response('formpage3.html')  


urls.py

[python]  view plain  copy
  1. from django.conf.urls.defaults import patterns, include, url  
  2. import views  
  3. from django.conf import settings  
  4.   
  5. urlpatterns = patterns('',  
  6.     url(r'^Resource/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_RESOURCE}),  
  7.       
  8.     url(r'^DealWithForm1','views.DealWithForm1'),  
  9.     url(r'^DealWithForm2','views.DealWithForm2'),  
  10.     url(r'^DealWithForm3','views.DealWithForm3'),  
  11. )  

settings.py

[python]  view plain  copy
  1. # Django settings for CheckFormBeforeSubmit project.  
  2.   
  3. import os  
  4. HERE = os.path.abspath(os.path.dirname(__file__))  
  5.   
  6. DEBUG = True  
  7. TEMPLATE_DEBUG = DEBUG  
  8. ...  
  9. STATIC_RESOURCE=os.path.join(HERE, "resource")  
  10. ...  
  11. MIDDLEWARE_CLASSES = (  
  12.     'django.middleware.common.CommonMiddleware',  
  13.     'django.contrib.sessions.middleware.SessionMiddleware',  
  14.     'django.middleware.csrf.CsrfViewMiddleware',  
  15.     'django.contrib.auth.middleware.AuthenticationMiddleware',  
  16.     'django.contrib.messages.middleware.MessageMiddleware',  
  17.     'django.middleware.csrf.CsrfResponseMiddleware',  
  18. )  
  19.   
  20. ROOT_URLCONF = 'CheckFormBeforeSubmit.urls'  
  21.   
  22. TEMPLATE_DIRS = (  
  23.     os.path.join(HERE,'template'),  
  24.     # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".  
  25.     # Always use forward slashes, even on Windows.  
  26.     # Don't forget to use absolute paths, not relative paths.  
  27. )  
  28. ...  


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值