javascript實現的簡單的表單驗證,javascript實現表單

來源:互聯網
上載者:User

javascript實現的簡單的表單驗證,javascript實現表單

表單驗證幾乎是不可缺少的,有的表單驗證是在後台完成的,有的則是使用JavaScript在在前端完成基本的驗證,這樣可以有效減輕伺服器的壓力,下面就介紹一下JS實現的最簡單的表單驗證。代碼執行個體如下:

<!DOCTYPE html><html><head><meta charset=" utf-8"><title>幫客之家</title><script type="text/javascript"> function chkform(){  if(document.getElementById("username").value==""){   alert("使用者名稱不可為空!");   return false;  }  if(document.getElementById("pw").value=="") {   alert("密碼不可為空!");   return false;  } } </script> </head> <body> <form action="" name="myform">  <table>   <tr>    <td>使用者名稱:</td>    <td><input type="text" name="username" id="username" /></td>   </tr>   <tr>    <td>密碼:</td>    <td><input type="password" name="pw" id="pw" /></td>   </tr>   <tr>    <td colspan="2"><input type="submit" value="提交"></td>   </tr>  </table> </form> </body> </html>

以上代碼實現了最基本的表單驗證,那就是不允許表單內容為空白,下面就簡單介紹一下它的實現過程:

一.在JavaScript代碼中,建立chkform()函數用來驗證表單,下面就簡單介紹一下次函數:

document.getElementById("username").value

以上代碼可以獲得id為username的對象的值,然後通過if語句判斷此值是否為空白,如果為空白則return false,這個語句非常重要,否則即使表單內容為空白,表單也會被提交,也就達不到驗證效果,第二個if判斷語句的作用也是如此,這裡就不介紹了。

二.onclick="return chkform()",此語句的作用是當點擊提交按鈕的時候就會執行chkform()函數用來驗證表單,這裡特彆強調一點不要忘記添加return。

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.