Create an XHTML form that collects a name, address, phone number, and zip code.
ID: 3722500 • Letter: C
Question
Create an XHTML form that collects a name, address, phone number, and zip code. The phone number must be input in the format of ddd-ddd-dddd and the zip code must be in the format of ddddd-dddd. Write a PHP script that checks the submitted information and verifies the format of the phone number and zip code. If the information correctly matches the format, display the information contained in the submitted form. If the data does not match the required format, return an error message exampling the format problem.
Explanation / Answer
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
</head>
<body>
<?php
$form_submitted = false;
$errors = array();
if(isset($_POST['form_submit'])){
$name = $_POST['name'];
$address = $_POST['address'];
$phone_number = $_POST['phone_number'];
$zip_code = $_POST['zip_code'];
if(!preg_match("^d{3}-d{3}-d{4}$",$phone_number)){
$errors['phone_number'] = "Invalid phone number.";
}
if(!preg_match("^d{5}-d{4}$",$zip_code))
$errors['zip_code'] = "Invalid zip code";
if(empty($errors)){
echo "<div><b>Name:</b> ".$name."</div>";
echo "<div><b>Address:</b> ".$name."</div>";
echo "<div><b>Phone Number: </b> ".$name."</div>";
echo "<div><b>Zip code: </b> ".$name."</div>";
$form_submitted = true;
}
}
if(!$form_submitted){
?>
<form method="POST" action="">
<div><strong>Name: </strong><input type="text" name="name" /></div>
<div><strong>Address: </strong><input type="text" name="address" /></div>
<div>
<strong>Phone Number: </strong><input type="text" name="phone_number" placeholder="ddd-ddd-dddd"/><br/>
<?php
if(isset($errors['phone_number'])){
echo "<div>".$errors['phone_number']."</div>";
}
?>
</div>
<div><strong>zip code: </strong><input type="text" name="zip_codde" placeholder="ddddd-ddd"/><br/>
<?php
if(isset($errors['zip_code'])){
echo "<div>".$errors['zip_code']."</div>";
}
?>
</div>
<div><input type="submit" value="Submit" name="form_submit"/></div>
</form>
<?php
}
?>
</body>
</html>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.