HTML 表單驗證可以經過 JavaScript 來完成。php
若是某個表單字段(fname)是空的,那麼該函數會發出一條警告消息,並返回 false,以防止表單被提交出去:html
function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == "") { alert("必須填寫姓名"); return false; } }
該函數可以在表單提交時被調用:
<form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> 姓名:<input type="text" name="fname"> <input type="submit" value="Submit"> </form>
<!DOCTYPE html> <html> <head> <script> function validateForm() { var x = document.forms["mysForm"]["fname"].value; if (x == "") { alert("必須填寫姓名!"); return false; } } </script> </head> <body> <form name="mysForm" action="/demo/action_page.php" onsubmit="return validateForm()" method="post"> 姓名:<input type="text" name="fname"> <input type="submit" value="提交"> </form> </body> </html>