JavaScript表单验证

首先了解下html的表单

<fieldset>
   <legend>用户注册legend>
    <form method="post" name="form" action="user.do?method=register" onSubmit="return beforeSubmit(this);">
     <table border="1" width="100%" cellspacing="0" cellpadding="0">
      <tr><td><label>用户名:<input type="text" name="username" value="">label>td>tr>
      <tr><td><label>密   码:<input type="password" name="password" value="">label>td>tr>
      <tr><td><label>重复密码:<input type="password" name="password2" value="">label>td>tr>
      <tr><td><input value="注册" type="submit"> <input type="reset" value="重置">td>tr>      
     table>
    form>
fieldset>

JavaScript表单验证_第1张图片

这是一个简单的用户注册表单

通过添加javascript代码达到验证的效果



<html>
    <head>
        <title>表单验证title>
    head>
    <body>
        <script type="text/javascript">
            function myFunction1(form)
            {
                // var x=document.forms["myForm"]["username"].value;
                var x=myForm.username.value;
                if(x==''){
                    alert("用户名不能为空!");
                    form.username.focus();
                    return false;
                }
                if(myForm.userpassword.value==''){
                    alert("密码不能为空!");
                    form.userpassword.focus();
                    return false;
                }
                if(myForm.userpassword.value.length<6){
                    alert("密码至少为6位,请重新输入!");
                    form.userpassword.focus();
                    return false;
                }
                if(myForm.userpassword2.value!=myForm.userpassword.value){
                    alert("两次输入的密码不一致,请重新输入!");
                    form.userpassword2.focus();
                    return false;
                }
                return true;
            }
        script>

        <fieldset>
            <legend>用户注册legend>
            <form action="user.do?method=register" name="myForm" method="POST" onSubmit="return myFunction1(this);">
                <table border="1" width="100%" cellpadding="0" cellspacing="0">
                    <tr><td>用户名: <input type="text" name="username" value="">td>tr>
                    <tr><td>密码:   <input type="password" name="userpassword" value="">td>tr>
                    <tr><td>重复密码: <input type="password" name="userpassword2" value="">td>tr>
                    <tr><td><input type="submit" value="注册">  <input type="reset" value="重置">td>tr>
                table>
            form>
        fieldset>

        
        
        
        <button onclick="myFunction()">点击这里button>
        <p id="demo">p>
        <script>
            function myFunction()
            {
                var carname="BMW";
                document.getElementById("demo").innerHTML=carname;
            }
        script>
    body>
html>

你可能感兴趣的:(学习笔记)