用js方法做提交表单的校验
生活随笔
收集整理的這篇文章主要介紹了
用js方法做提交表单的校验
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基礎知識:
原始提交如下:
<form action="<%=basePath %>puser/register" method="post"><input placeholder="Name" name="realname"> <input type="email" placeholder="Email" name="email"><input type="password" placeholder="Password" name="password"><input type="password" placeholder="Again input Password" ><button type="submit"></button></form>
說明:
form是一個表單,用來發送http請求。直觀的說,只要用form將需要提交到服務器的標簽包圍,當提交的時候,就會向服務器發送有name屬性的數據。所以,input內容提交必須有name屬性。
action:服務器接口路徑;
method:選擇發送請求的方式,默認是get,通常用post。get請求會在地址欄顯示參數,并且有長度限制。post則沒有。
id:標識標簽元素
當提交后,服務器就會得到:username=填的用戶名 & password=填的密碼
當點擊提交后,form數據就會發送。通常提交前要校驗數據。比如長度規則等。所以需要js。
js校驗:
???????????方法:
在from屬性后面接著添加οnsubmit="return false;"屬性.表示不提交。true則相反。這里可以用一個方法替換。變成:
<form action="<%=basePath %>puser/register" method="post" onsubmit="return compare();">
js方法部分:
<script type="text/javascript">function compare(){var password = document.getElementById("password").value;var password2 = document.getElementById("password2").value;if(password!=password2){alert("兩次輸入的密碼不一致!!");return false;} }
</script>
除此之外還有使用ajax提交,在那之前進行校驗(關于ajax請查看我的其他文章),以上。
總結
以上是生活随笔為你收集整理的用js方法做提交表单的校验的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UUID的使用及其原理
- 下一篇: JS Uncaught SyntaxE