如何使用javascript验证我的表单

时间:2015-01-15 18:08:53

标签: javascript php html css

我想使用javascript验证我的表单。在表单提交之前,我希望服务器在字段输入下方显示错误(如果有的话)。我可以在这段代码中使用外部javascript文件吗? / p>

这是我的代码:

<!DOCTYPE HTML> 
    <html>
    <head>
    <style>
    .error {color: #FF0000;}
       .label_text {
float: left;
width: 44%;
text-align:right;
font-weight:bold;
color:purple;
}
.register1{
text-align:center;}
.header_tag{text-align:center;
font-weight:bold;
color:green;}
.header_tag1{ margin:10px;
float:left;
text-align:center;
font-weight:bold;
color:green}
.register_section{border:1px solid black;
text-align:center;
padding:20px;
margin-left:30%;
margin-right:30%;
float:none;
height:350px;
}
.input{ text-align:left;
float:left;
border:2px solid black;
}
.gender{float:left;}
.register{ float:left;
text-align:center;
color:green;
font-weight:bold;
padding:10px;
margin-left:36%;}
    </style>
    </head>

    <body> 

    <?php
    // define variables and set to empty values
    $nameErr = $passwordErr = $password2Err = $emailErr = $genderErr = "";
    $name = $password = $confirmpassword = $email = $gender = $description =  "";
$result="";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $username = "";
    $password = "";
    $hostname = ""; 
    //connection to the database
    $dbhandle = mysql_connect($hostname, $username, $password) 
     or die("Unable to connect to MySQL");
    echo "Connected to MySQL<br>";
    //select a database to work with
    $selected = mysql_select_db("test",$dbhandle) 
      or die("Could not select test");

       if (empty($_POST["name"])) {
         $nameErr = "Name is required";
       } else {
         $name = test_input($_POST["name"]);
         if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
           $nameErr = "Only letters and white space allowed"; 
         }
       }
       if (empty($_POST["password"])) {
         $passwordErr = "Password is required";
       } else {
         $password = test_input($_POST["password"]);  
       }
       if (empty($_POST["confirmpassword"])) {
         $password2Err = "Confirm Password";
       } else {
         $password = test_input($_POST["confirmpassword"]);   
       }
       if ($_POST['password']!= $_POST['confirmpassword'])
     {
         echo("Oops! Password did not match! Try again. ");
     }

       if (empty($_POST["email"])) {
         $emailErr = "Email is required";
       } else {
         $email = test_input($_POST["email"]);
         if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
           $emailErr = "Invalid email format"; 
         }
       }

       if (empty($_POST["description"])) {
         $comment = "";
       } else {
         $comment = test_input($_POST["description"]);
       }

       if (empty($_POST["gender"])) {
         $genderErr = "Gender is required";
       } else {
         $gender = test_input($_POST["gender"]);
       }

     if (empty($genderErr))
     {if (empty($emailErr)){
       if (empty($password2Err)){
          if (empty($passwordErr)){
              if (empty($nameErr)){

           $result=mysql_query("SELECT * FROM person WHERE username ='$name' AND password='$password'AND Email='$email'");
     if (mysql_num_rows($result)==0  ) 
      { // IF no previous user is using this username.


                $result1=mysql_query("INSERT INTO person(username,password,Email,Gender) VALUES ( '$name', '$password','$email','$gender')");


               {  if($result1)
                 ////If the Insert Query was successfull.

                    // Send an email

                    // Finish the page:
                   { 
                   echo '<div class="success">Thank you for registering! A confirmation email has been sent to ' . $email . ' </div>';

                } 
                else 
                { // If it did not run OK.
                    echo '<div class="errormsgbox">You could not be registered due to a system error. We apologize for any inconvenience.</div>';
                }
              }

            } 


            // The username is not available.
            else
            {    echo '<div class="errormsgbox" >That username has already been registered.</div>';
          }
          }
       }
     }
       }
     }
   }



    function test_input($data) {
       $data = trim($data);
       $data = stripslashes($data);
       $data = htmlspecialchars($data);
       return $data;
    }

    ?>
<div class="register1">
     <h2 class="header_tag">REGISTER HERE</h2>
    <p><span class="error"></span></p>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
          <div class="register_section">
     <div class="label_text">
      Name:<span class="error">*  </div>
    <div class="input">
    <input type="text" name="name"><br> </div>
       <span class="error"><?php echo $nameErr;?></span>
       <br><br>
       <div class="label_text">
       Password:<span class="error">*  </div>
        <div class="input">
        <input type="text" name="password"><br> </div>
       <span class="error"><?php echo $passwordErr;?></span>
       <br><br>
      <div class="label_text">
       Confirm Password:<span class="error">*  </div>
      <div class="input">
       <input type="text" name="confirmpassword"><br> </div>
       <span class="error"><?php echo $password2Err;?></span>
       <br><br>

       <div class="label_text">
       E-mail:<span class="error">*  </div>
      <div class="input">
      <input type="text" name="email"><br></div>
       <span class="error"><?php echo $emailErr;?></span>
       <br><br>
      <div class="label_text">
       Description: </div>
        <div class="input">
        <textarea name="description" rows="5" cols="22"></textarea> </div>
       <br><br>
       <div class="label_text">
       Gender:<span class="error">*  </div>
       <div class="gender">
       <input type="radio" name="gender" value="female">Female
       <input type="radio" name="gender" value="male">Male
       </div>
       <span class="error"><?php echo $genderErr;?></span>
       <br><br><br>
       <div class="register">
       <input type="submit" name="submit" value="REGISTER"> 
      <br>
      <h3 class="header_tag1">"<a href="login_access.php">Back to Login</a>
      </div>

       </div>
       </div>
    </form>



    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

您要做的是正确地称为客户端验证

最简单的方法是使用第三方库,例如FormValidation

例如,要验证您的电子邮件字段,您可以执行以下操作:

<form method="post" id="register_user" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
    ...
    <input type="text" name="email" data-fv-emailaddress="true" data-fv-emailaddress-message="The value is not a valid email address" />
    ...
</form>

<script>
$('#register_user').submit(function() {
    $('#register_user').formValidation();
});
</script>

当然,您需要确保为jQuery,FormValidation和合适的内容框架(例如Bootstrap)包含必要的CSS和JS库。

为了记录,如果您只是在寻找基本的用户管理脚本,我强烈建议您避免重新发明轮子。获取现有脚本,例如UserFrosting,然后根据您的需要进行修改。