drlnsli18864734
drlnsli18864734
2015-12-14 11:50

单击提交按钮时,如何使我的所有文本框都不为空

  • php
  • html

I'm new to PHP and I want to know How can i make my all my textbox not empty when i click the submit button. When i enter special characters like space,/;>< and etc all the textbox becomes empty. I only want that textbox that i input special characters to be empty not all the textbox.

HERE is my code

function.php

<html>
<head>
    <style>
        .error {color: #FF0000;}
    </style>
</head>
<body> 
    <h2>PHP Form Validation Example</h2>
    <p><span class="error">* required field.</span></p>
    <form method="post" action="1.php"> 
         <label>Name:</label> <input type="text" name="name"> <span class="error">* <?php echo $_SESSION['name'];?></span>
         <br><br>
         <label>E-mail:</label> <input type="text" name="email"> <span class="error">* <?php echo $_SESSION['email'];?></span>
         <br><br>
         <label>Website:</label> <input type="text" name="website"> <span class="error"><?php echo $_SESSION['website'];?></span>
         <br><br>
         <label>Comment:</label> <input type="text" name="comment">
         <br><br>
         <label>Gender:</label>
         <input type="radio" name="gender" value="female">Female
         <input type="radio" name="gender" value="male">Male
         <span class="error">* <?php echo $_SESSION['gender'];?></span>
         <br><br>
         <input type="submit" name="submit" value="Submit"> 
    </form>
</body>
</html>
<?php 
unset($_SESSION['name']);
unset($_SESSION['email']);
unset($_SESSION['website']);
unset($_SESSION['comment']);
unset($_SESSION['gender']);
?>

1.php

<?php
session_start();
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";


if ($_SERVER["REQUEST_METHOD"] == "POST") {

     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
          {$_SESSION['name']= "Name is requiredassssssssssssssss";}
     }

     $email = test_input($_POST["email"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$email)) {
          {$_SESSION['email']= "email is requiredassssssssssssssss";}
     }

     $website = test_input($_POST["website"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$website)) {
          {$_SESSION['website']= "website is requiredassssssssssssssss";}
     }
}


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

if ((!preg_match("/^[a-zA-Z ]*$/",$name)) ||  (!preg_match("/^[a-zA-Z ]*$/",$email)) || (!preg_match("/^[a-zA-Z ]*$/",$website)))
{
    header("Location: function.php");
}

echo $_POST['name'];
echo $_POST['email'];
echo $_POST['website'];
?>
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答