PHP Form Required

  • In PHP form some data fields are required to be filled. Here we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields):
  • <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

    Name: <input type="text" name="name">

    <span class="error">* <?php echo $nameErr;?></span>



    <input type="text" name="email">

    <span class="error">* <?php echo $emailErr;?></span>



    <input type="text" name="website">

    <span class="error"><?php echo $websiteErr;?></span>


    <label>Comment: <textarea name="comment" rows="5" cols="40"></textarea>



    <input type="radio" name="gender" value="female">Female

    <input type="radio" name="gender" value="male">Male

    <span class="error">* <?php echo $genderErr;?></span>


    <input type="submit" name="submit" value="Submit">

  • The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?".