Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

frits vd Velden
frits vd Velden
1,860 Points

Make form fields mandatory

Hi, been trying everything, well almost everything. How do I make these fields mandatory? Thanks a bunch!

<?php
if (isset($_POST['zendform'])) 
{      $fout = false; // To see what's wrong
    $zendform = "Bedrijf: " . $_POST["bedrijf"] . "\r\n";
    $zendform .= "Naam: " . $_POST["naam"] . "\r\n";
    $zendform .= "Adres: " .  $_POST["adres"] . "\r\n";
    $zendform .= "postcode: " . $_POST["postcode"] . "\r\n";
    $zendform .= "Plaats: " . $_POST["plaats"] . "\r\n";
    $zendform .= "Email: " . $_POST["mail"] . "\r\n";
    $zendform .= "Telefoon: " . $_POST["tel"] . "\r\n";
    $zendform .= "Starnummer: " . $_POST["star"] . "\r\n";
    $zendform .= "IBAN: " . $_POST["iban"] . "\r\n";
    foreach($_POST["autoincasso"] as $value)
    {
        $zendform .= "Autoincasso: " . $value . "\r\n";  
    }
    foreach($_POST["factuur"] as $value)
    {
        $zendform .= "Factuur:" . $value . "\r\n";  
    }
    $to      = 'mail@mailadress.com';
    $subject = 'Formulier';
    $headers = 'From: mail@mailadress.com' . "\r\n" .
        'Reply-To:mail@mailadress.com' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $zendform, $headers);
    mail ('mail@mailadress.com', $subject, $zendform, $headers);
    echo 'Your form has been send.';
    }
?>

2 Answers

Paul Yorde
Paul Yorde
10,497 Points

Hi frits,

the quickest way is to add the 'required' attribute in your input tag with html5 like this:

<form>
  <input type="text" name="naam" required>
  <input type="submit">
</form>

This first line of code also makes sure that the form was actually submitted. It then checks to see if the 'naam' value has any data (meaning it could be malicious data). if it is empty, then the error message is set. if is is not empty, then the name variable is set with what ever the user desired to give you (again could be malicious).

//You would use PHP like this:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["naam"])) {
    $nameErr = "Name is required";
  } else {
    $name = $_POST["name"];
  }
}

// then in the html like this:
<form>
<input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
</form>
frits vd Velden
frits vd Velden
1,860 Points

Allright, thanks for the advice Paul. the first one is easy enough :)