PHP - Server-side validation

After the user submits a form, the data is sent to the server.
The PHP script checks the data and returns an error message if the data is invalid.

Code - HTML

<form action="test.php" method=get>
	First name: <input type="text" name="firstname"><br />
	Last name: <input type="text" name="lastname"><br />
	<input type="submit">
</form>

Code - PHP

<?php
	$firstname = $_GET['firstname'];
	$lastname = $_GET['lastname'];

	if (empty($firstname) || empty($lastname)) {			// check if fields are empty, symbol || means OR
		echo "Both fields are required!";
	} else {							// if both fields are not empty
		echo "Hello $firstname $lastname!";
	}
?>

Demo

Open in new window

Task

Create an HTML form with two fields "First name" and "Last name".
Criteria:
- User must enter both fields.
- Length of the fields must be greater than 2 and less than 20 characters.
- Name must contain only letters.

Return "Hello Firstname Lastname!" if both fields are not empty.
Provide a back link to the form if any field is invalid.