Given the following input values from a form, create a method or methods to validate the input based on their requirements. Throw an exception if any data is invalid.
1.1
name
: is required
1.2 must be first name AND last name2.1
2.2 is a valid email address3.1
3.2 is a Twitter handleThe input data will be in the following format:
$input = [ 'name' => '...', 'email' => '...', 'twitter' => '...' ];
This is the code snippet I worked on. How can I improve my code? I am not allowed to include
or use any other files.
<!DOCTYPE html>
<html>
<head>
<title>PHP Form Validation</title>
</head>
<body>
<?php
$name = '';
$email = '';
$twitter = '';
$nameError ="";
$emailError ="";
$twitterError ="";
class dataException extends Exception
{
public function errorMessage()
{
$message = $this->getMessage();
return $message;
}
}
try
{
if(isset($_POST['submit']))
{
if (empty($_POST["name"]) && empty($_POST["email"]))
{
throw new dataException('Name and Email are required');
}
if (empty($_POST["name"]))
{
throw new dataException('Name is required');
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
throw new dataException('Only letters and white space allowed');
}
else
{
if(str_word_count($name)!=2)
{
throw new dataException('FirstName and LastName is required');
}
}
}
if (empty($_POST["email"]))
{
throw new dataException('Email is required');
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
{
throw new dataException('Email is invalid');
}
}
//checked vs internet.
$twitter = test_input($_POST['twitter']);
if (!isset($_POST['twitter']) || $_POST['twitter'] === '')
{
$twitter = '';
}
else
{
if (!preg_match('/^(\@)?[A-Za-z0-9_]+$/', $twitter))
{
throw new dataException('Invalid twitter handle');
}
}
}
}
catch (dataException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//php code ends here
?>
<form action="" method="post">
Name (FirstName and LastName):
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>">
* <?php echo $nameError;?>
<br>
<br>
E-mail:
<input type="text" name="email" value="<?php echo htmlspecialchars($email);?>">
* <?php echo $emailError;?>
<br>
<br>
Twitter:
<input type="text" name="twitter" value="<?php echo htmlspecialchars($twitter);?>">
<?php echo $twitterError;?>
<br>
<br>
<input type="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</body>
</html>