Username Keeps being Validated as a Name - php

//This is my php for the registration: <?php
/* Program name: checkBlankOnly_2.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "firstname")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if($blank_array > 0)
{
$message = "<p style='color: red; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("logic.inc");
exit();
}
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt2 = "/^[a-z]\w{2,23}[^_]$/i";
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$pass_patt = "/^[a-zA-Z][0-9a-zA-Z_!$##^&]{5,20}$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$addr_patt = "/^[A-Za-z0-9 .,'-]{1,50}$/";
$zip_patt = "/^[0-9]{5}(\-[0-9]{4})?$/";
$postal_patt = "/^[A-Za-z0-9]{6}$/";
$email_patt = "/^.+#.+\\..+$/";
$radio_patt = "/Canada|USA/";
if(preg_match("/uname/i",$field))
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif phone format check
if(preg_match("/country/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if($error_array > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("logic.inc");
exit();
}
else
{
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die("Couldn't Connect to Server");
foreach($clean_data as $field => $value)
{
$clean_data[$field] = mysqli_real_escape_string($cxn,$value);
}
$sql = "INSERT INTO users (uname,password,lastname,firstname,city,address,state_province,country,phone,email,date) VALUES ('$clean_data[uname]','$clean_data[password]','$clean_data[lastname]','$clean_data[firstname]','$clean_data[city]','$clean_data[address]','$clean_data[state_province]','$clean_data[country]','$clean_data[phone]','$clean_data[email]','$clean_data[date]')";
$result = mysqli_query($cxn,$sql)
or die("Couldn't Execute Query");
include("stored.inc");
}
}
else
{
include("logic.inc");
}
?>
\\ This is my HTML code:
<!doctype html>
<?php
ini_set("display_errors","on");
error_reporting(E_ALL | E_STRICT);
ini_set("include_path","./includes");
include("dbinfo.inc");
?>
<?php
/* Program Name: logic.inc
* Created by: Clayton Korth
* Created On: 2022-05-20
* Description: Defines a form that collects a user's information */
$labels = array ("uname" => "Username","firstname" => "First Name","lastname" => "Last Name","address" => "Address","city" => "City","zip_postal" => "Zip Code","phone" => "Phone","email" => "Email");
$country = array("Canada","US");
$submit = "Submit Information";
$empty_array = array();
$blank_array = array();
?>
<?php
$cxn = mysqli_connect($host,$user,$passwd,$dbname)
or die ("Couldn't Connect to Server");
$query = "SELECT DISTINCT name FROM states ORDER BY `id` ASC";
$result = mysqli_query($cxn,$query) or die ("Couldn't Execute Query.")
?>
<html>
<head>
<style type='text/css'>
<!--
form {
margin: 1.5em 0 0 0;
padding: 0;
align-content: center;
}
.field {padding-bottom: 1em;}
h1 {text-align: center;}
label {
font-weight: bold;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
#submit {margin-left: 35%}
--></style>
<meta charset="utf-8">
<title>Form Script</title>
</head>
<body>
<?php
/* loop that displays the form */
echo "<div class='row'><div class='col-lg-6>'";
echo "<h3>Sign Up Form</h3>";
echo "<form id='sForm' form action='checkBlankOnly2.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field' style='font-weight: bold;'>$label</label>
<input id='$field' name='$field' type='text' placeholder='$label'
size='42' /></div>";
if($field == "uname")
{
echo "<div class='field'><label for='password'>Password</label><input id='password' placeholder='Password' name='password' type='password' size='42'></div>";
}
if($field == "city")
{
echo "<form action='checkBlankOnly2.php' method='POST' style='margin-left: 3em'>
<label for'name' style='font-weight: bold'>State/Province:</label>
<select id='name' name='name' style='margin-top: 3em'>";
while($row = mysqli_fetch_assoc($result))
{
extract($row);
echo "<option value='$name'>$name</option>";
}
echo "</select>";
echo "<div class='field'><label for='country'>Country</label><input type='radio' name='country' checked='checked' value='Canada' >$country[0]
<input type='radio' name='country' value='US' style='margin-left: 1.5em'>$country[1]</div>";
}
}
echo "<div class='field'><input type='hidden' name='submitted' value='yes'</div>";
echo "<div id='submit'><input type='submit' value='$submit'></div>";
echo "</div></div>"
?>
</body>
</html>
Above is my code for my registration.php as I am tasked to create an Login Application. What happens is that when I submit the form it validates everything except the username causing it to be validated by using name instead of username. I am wondering if I had done something wrong with my code. I am fairly new to PHP and Dynamic Web Design

You'll probably want to read up on regular expressions, which is what preg_match() uses.
https://www.php.net/manual/en/function.preg-match.php
The following code will first get a positive match of uname against /uname/i, and then compare the value against $name_patt2, but then it will also get a positive match of uname against /name/i, because the pattern isn't anchored to the beginning with ^.
if(preg_match("/uname/i",$field))
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
You can go one of 3 ways, if you're leaving the rest of the program alone:
One is to replace the $field checks with anchored regexes, like this:
if(preg_match("/^uname/i", $field))
...
A second option is to elseif so you won't check the other patterns for $field if the first one already matched:
if(preg_match("/uname/i",$field))
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
elseif(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
The third option (depending on what the field naming actually looks like), would be to use exact string matches instead of regex matches:
if($field == "uname")
{
if(!preg_match($name_patt2,$value))
{
$error_array [] = "$value is not a valid username";
}
}
if($field == "name")
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}

Related

Why is my echo variable not displaying upon submission?

I am working on a school project for php I have 2 files, checkBlank.php and form.php. everything displays correctly and its submitting the form well, but its not displaying the echo $message for fields that were not filled in.
Here is the code:
if(isset($_POST['submitted']) and $_POST['submitted'] == 'yes') {
foreach($_POST as $field => $value) {
if(empty($value)) {
$blank_array[] = $field;
}
else {
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($blank_array) > 0) {
$message = "<p style ='color: red; margin-bottom: 0; font-weight: bold'>
You have not filled in all the fields.
Please fill in the:
<ul style='color: red; margin-top: 0; list-style: none' >";
foreach($blank_array as $value) {
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include ("form.inc");
exit();
}
echo "All fields contain information";
}
else {
include("form.inc");
}

Keep values in input fields - php array

I have a php array that includes inputs for posting. It uses a counter for each array record, and this counter is applied to the name of the input to be used in performing some actions with the post - this is working great.
The issue is that I would like to keep the users' existing inputs and re-populate the input fields in the array if their post doesn't pass validation.
I have done this before with static fields, simply storing the post variable and echoing it in the "value" --- but I can't figure out how to do this when working with an array. Anyone have any ideas?
$counter = 0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr height='60'>";
echo "<td class='mainlist'><input type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt'></td>";
echo "</tr>";
$counter = $counter + 1;
}
echo "</table>";
Full code per request:
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$userid = $_SESSION['login_user'];
$companyid = $_POST['companyid'];
$options = $_POST['options'];
$counter = $_POST['hiddencounter'];
$runningtotal=0;
$totaloptions = array_sum($options);
$result = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$checknewcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."' and company_id = '" .$companyid[$i]."'");
if($checknewcompanies->num_rows == 1)
{ // do nothing
}
else
{
$runningtotal = $runningtotal + 1;
}
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$checkcurrentcompanies = mysqli_query($connection, "SELECT company_id FROM user_company_total_invested WHERE user_id = '".$userid."'");
$countcompanies = $checkcurrentcompanies->num_rows;
$countcheck = $runningtotal + $countcompanies;
if($countcheck <= 4)
{
while($row = mysqli_fetch_array($result))
{
$balance = $row['options_balance'];
}
if ($totaloptions>$balance)
{
$notenoughoptions= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You don't have enough options! Try investing less!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i])){ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else {
if(!ctype_digit($options[$i]) or !is_numeric($options[$i])){
$charactercheck= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! Please enter only positive numbers to invest!</div>";
}
else {
$checkcompanies = mysqli_query($connection, "SELECT company_id FROM company_main WHERE company_id = '".$companyid[$i]."'");
if($checkcompanies->num_rows != 1)
{
$companynotexist= "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! That company doesn't exist!</div>";
}
else
{
// loop through array
for ($i=0; $i<$counter; $i++)
{
if(empty($options[$i]))
{ /* IF NO INPUT ON OPTIONS */
/* DO NOTHING */
}
else
{
$query = "INSERT INTO user_company_invested(user_id, company_id, user_company_options_invested)
VALUES($userid,$companyid[$i],$options[$i])";
mysqli_query($connection, $query);
} /* END OF ELSE IF NOT EMPTY OPTIONS */
} /* END OF FOR LOOP */
$balancecheck = mysqli_query($connection, "SELECT options_balance FROM user_options_balance WHERE user_id = '".$userid."'");
while($row = mysqli_fetch_array($balancecheck))
{
$balance2 = $row['options_balance'];
}
if($balance2 > 0)
{
header('Location: user_invest.php');
}
else
{
header('Location: user_market.php');
}
} // end company check
} //end character check
} //end empty option check
} //end loop
} /* END OF NOT ENOUGH OPTIONS CHECK */
}
else
{
$toomanycompanies = "<div style='background-color:#FF0000; border-radius: 15px; padding: 10px; color: #FFFFFF; font-size: 12px;'>Oops! You can invest in a maximum of 4 companies per week. Please choose fewer companies, or invest more in some of your existing companies!</div>";
/* echo "Maximum number of companies you can invest in is 4";
echo "<br />";
echo "Companies you already are invested in: ".$countcompanies;
echo "<br />";
echo "New companies you are trying to invest in: ".$runningtotal;
echo "<br />";
echo "Total: ".$countcheck;*/
}
} /* END OF ISSET CHECK */
else
{
}
?>
<?php
$result = mysqli_query($connection,"SELECT * from company_main");
$counter=0;
echo "<form method='post'>";
echo "<table class='mainlist' width='680'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr height='60'>";
echo "<td class='mainlist' width=140 align='center'>" . "<img src='".$row['company_logo']."' width='40'/>" . "</td>";
echo "<td class='mainlist' align='left' width=390 style='font-size: 15px;'>" . $row['company_name'] . "</td>";
echo "<input type=hidden name=companyid[$counter] value=" . $row['company_id'] . " />";
echo "<td class='mainlist'><input value='{$_POST['options[$counter]']}' type=text name=options[$counter] autocomplete=off onclick='this.select()' class='txt' style=' background-color: #FCFCFC;
border: solid 1px #CCCCCC;
font-size: 12px;
padding: 5px;
height: 20px;
text-align: right;'></td>";
echo "</tr>";
$counter=$counter+1;
}
echo "</table>";
echo "<input type='hidden' name='hiddencounter' value='$counter'>";
echo "
<table>
<tr>
<td width='630' height='50'></td>
<td align='right' width='60' style='color: #848580; font-size: 20px;'>Total: </td>
<td align='right' width='40' style='color: #94D90B; font-size: 20px; font-weight: bold; padding-right:20px;'><span id='sum'>0</span></td><td width='10'></td>
</tr><tr height='20px'></tr><tr>
<td width='570' align='center' style='color: #94D90B; font-size: 12px;'>";?>
<?php echo $notenoughoptions; ?>
<?php echo $charactercheck; ?>
<?php echo $toomanycompanies; ?>
<?php echo "
</td>
<td colspan='2' width='100' align='right'><input name='userinvestoptionsdynamic' type='submit' value='Invest!'></td><td width='10'></td>
</tr>
<tr height='20px'></tr>
</table>";
echo "</form>";
?>
The correct syntax is:
echo "{$arrayname($keyname)}";
So for example echo('value=' . $_POST['options'][$counter]); becomes:
echo "value={$_POST['options'][$counter]}";

Fetch data from mysql to textarea, but if not exist print null

I made some little translator.
And if word exist in database all is ok. But if word didnt exist in database, word isnt printed. I add some code to print if result is empty but didnt work.
Any idea why word that not exist in database isnt printed?
Here is code:
<p><form method="post" action="prevedi.php">
<textarea id="prevedi" name="prevedi" style="margin: 2px; height: 137px; width: 380px;">
<?php
echo htmlentities($_POST['prevedi']);
?>
</textarea>
<textarea id="prevod" disabled="disabled" name="prevod" style="margin: 2px; height: 137px; width: 380px; border: 0px;" readonly>
<?
if (isset($_POST['prevedi'])) {
//Kreci
$prevedi = htmlentities($_POST['prevedi']);
$prevedi = explode(" ",$prevedi);
foreach ($prevedi as $word) {
$slovo = $word[0];
$result = mysqli_query($con,"SELECT * FROM $slovo WHERE srpski='$word'");
if (!empty($result)) {
while($row = mysqli_fetch_array($result))
{
$prevod .= $row['romski']." ";
}
}
else
{
$prevod .= "".$word." ";
}
}
echo $prevod;
//Kraj isset
}
?>
</textarea><br>
<input name="translate" type="submit" value="Translate"/>
</form>
</p>
Because your result is not empty. You should check if $result number of rows is > 0
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($result)){
$prevod .= $row['romski']." ";
}
}else{
$prevod .= $word." ";
}
i think you have to initialize $prevod before assigning it the way you did.
$prevod = "";
if (!empty($result)) {
while($row = mysqli_fetch_array($result))
{
$prevod .= $row['romski']." ";
}`enter code here`
}
else
{
$prevod .= "".$word." ";
}
}
echo $prevod;

PHP drop down list using array's and foreach (else and for) code

I'm taking a course called "Dynamic Web Development with PHP" and after getting an F for an exercise, I wish if you could help me with the following.
I have a php file and an inc file (that shows the form).
What I can't figure out how to resolve is the drop-down lists of the country and state / province, which should work like this:
If country USA is selected populate US states.
If country CAN is selected populate Canadian provinces.
I've made to array's one is states_list (USA) and province_list (CAN)
My teacher asking me to use the if statement to show the drop-down field.
Exemple:
foreach($labels as $field => $label)
{
if($field == "state")
{
echo html code for the drop-down list
}
else
{
echo html code for a text field
}
}
My inc file:
<?php
/* Program name: form_data.inc
* Description: Defines the form that collects a user's
* personal information.
*/
$labels = array( "firstName" => "First Name",
"lastName" => "Last Name",
"street" => "Street",
"city" => "City",
"zip" => "Postal Code",
"country" => "Country",
"state" => "State",
"email" => "E-mail",
"phone" => "Phone",);
$country_list = array("USA" => "United States",
"CAN" => "Canada",);
$state_list = array( "AL"=>"AL",
"AK"=>"AK",
"AZ"=>"AZ",
"AR"=>"AR",
"CA"=>"CA",
"CO"=>"CO",
"CT"=>"CT",
"DE"=>"DE",
"DC"=>"DC",
"FL"=>"FL",
"GA"=>"GA",
"HI"=>"HI",
"ID"=>"ID",
"IL"=>"IL",
"IN"=>"IN",
"IA"=>"IA",
"KS"=>"KS",
"KY"=>"KY",
"LA"=>"LA",
"ME"=>"ME",
"MD"=>"MD",
"MA"=>"MA",
"MI"=>"MI",
"MN"=>"MN",
"MS"=>"MS",
"MO"=>"MO",
"MT"=>"MT",
"NE"=>"NE",
"NV"=>"NV",
"NH"=>"NH",
"NJ"=>"NJ",
"NM"=>"NM",
"NY"=>"NY",
"NC"=>"NC",
"ND"=>"ND",
"OH"=>"OH",
"OK"=>"OK",
"OR"=>"OR",
"PA"=>"PA",
"RI"=>"RI",
"SC"=>"SC",
"SD"=>"SD",
"TN"=>"TN",
"TX"=>"TX",
"UT"=>"UT",
"VT"=>"VT",
"VA"=>"VA",
"WA"=>"WA",
"WV"=>"WV",
"WI"=>"WI",
"WY"=>"WY");
$province_list = array( "AB"=>"AB",
"BC"=>"BC",
"MB"=>"MB",
"NB"=>"NB",
"NL"=>"NL",
"NS"=>"NS",
"NT"=>"NT",
"NU"=>"NU",
"ON"=>"ON",
"PE"=>"PE",
"QC"=>"QC",
"SK"=>"SK",
"YT"=>"YT");
$radios = array( "New", "Changed");
$submit = "Submit Data";
?>
<html>
<head>
<title>Form</title>
<style type='text/css'>
<!--
body {
background: #242523;
font-family: Tahoma, Geneva, sans-serif;
}
form {
width: 500px;
margin: auto;
padding: 10px 0 25px 0;
-webkit-border-radius: 7px/9px;
-moz-border-radius: 7px/9px;
border-radius: 7px/9px;
background-color: #fff;
}
.field {padding-bottom: 1em;
font-weight: normal;
font-size:14px;
}
label {
font-weight: normal;
font-size:14px;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
input {
}
h3 {
color:#C00;
text-align: center;
font-size:20px;
padding-bottom: 10px;
}
#submit {
margin-left: 22%;
}
-->
</style>
</head>
<body>
<br>
<?php
/* loop that displays the form */
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
echo "<h3>Personal information</h3>";
foreach($labels as $field => $label)
{
echo "<div class='field'><label for='$field'>$label</label>
<input id='$field' name='$field' type='text' value='".#$$field."'
size='50%' maxlength='50' /></div>\n";
}
echo "<div class='field'>
<input type='radio' name='status' checked='checked'
value='new' style='margin-left: 25%'/>$radios[0]
<input type='radio' name='status'
value='changed' style='margin-left: 25%' />$radios[1]</div>\n";
echo "<div class='field'>
<input type='hidden' name='submitted' value='yes' /></div>\n";
echo "<div id='submit'>
<input type='submit' name='submitButton' value='$submit'></div>";
?>
</form>
</body>
</html>
My PHP file:
<?php
/* Program name: checkBlank.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "firstName")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($blank_array) > 0)
{
$message = "<p style='color: white; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("form_data.inc");
exit();
} // endif missing information
/* format check */
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$addr_patt = "/^[A-Za-z0-9 .,'-]{1,50}$/";
$city_patt = "/^[A-Za-z' -]{1,50}$/";
$postal_patt = "/^[A-Za-z0-9-]{1,10}$/";
$state_patt = "/^[A-Za-z]{2}$/";
$province_patt = "/^[A-Za-z]{2}$/";
$country_patt = "/^[A-Za-z' -]{1,50}$/";
$email_patt = "/^.+#.+\\..+$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$radio_patt = "/(new|changed)/";
/* Checks first and last names */
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
/* Checks address */
if(preg_match("/street/i",$field))
{
if(!preg_match($addr_patt,$value))
{
$error_array[] = "$value is not a valid address";
}
}
/* Checks city */
if(preg_match("/city/i",$field))
{
if(!preg_match($city_patt,$value))
{
$error_array[] = "$value is not a valid city name";
}
}
/* Checks postal code */
if(preg_match("/zip/i",$field))
{
if(!preg_match($postal_patt,$value))
{
$error_array[] = "$value is not a valid potal code";
}
}
/* Checks country names*/
if(preg_match("/country/i",$field))
{
if(!preg_match($country_patt,$value))
{
$error_array[] = "$value is not a valid country";
}
}
/* Checks state and province names */
if(preg_match("/state/i",$field))
{
if(!preg_match($state_patt,$value))
{
$error_array[] = "$value is not a valid state";
}
}
if(preg_match("/province/i",$field))
{
if(!preg_match($province_patt,$value))
{
$error_array[] = "$value is not a valid province";
}
}
/* Checks email address */
if(preg_match("/email/i",$field))
{
if(!preg_match($email_patt,$value))
{
$error_array[] = "$value is not a valid e-mail address";
}
}
/* Checks phone number */
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif formats check
if(preg_match("/status/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if(#sizeof($error_array) > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("form_data.inc");
exit();
}
else
{
echo "Data is all okay";
}
/* displays all the information passed from a form */
echo "<ol>";
foreach($_POST as $field => $value)
{
echo "<li> $field = $value</li>";
}
echo "</ol>";
}
else
{
include("form_data.inc");
}
?>
you can make two drop down list one for country and two for states.
first drop down list will have three items
select country (as selected)
USA
CAN
second drop down list will be empty and it reload by using ajax only if you select a country ( USA - CAN )
else second down list will return empty again
With such a small amount of data, it doesn't really even need to be an Ajax call to fetch the state/province list. Just simply load them into the page as a JSON object and swap the list.
This is a rough draft, not finished or polished code:
<script src="path/to/jquery.js"></script>
<script>
var stateMap = {
"USA": [ { "AL" : "AL"} .....],
"CAN": [ { "AB" : "AB" }, .... ]
};
function setStates(country) {
var newOptions = stateMap[country];
var states = $('#states');
states.empty();
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
}
// initialise on document load...
$(function() {
setStates( "USA");
});
// set state list on country change....
$('#country').change( function() {
var country = $( this ).val();
setStates( country);
}
</script>
<body>
<select id="country">
<option value="USA">USA</option>
<option value="CAN">Canada</option>
</select>
<select id="states">
</select>
</body>

PHP phone pattern validation error

I have an inc file (test_form4.inc) which defines the form that collects a user's name and phone number.
<!doctype html>
<?php
/* Program name: form_test4.inc
* Description: Defines a form that collects a user's
* name and phone number.
*/
$labels = array( "first_name" => "First Name",
"middle_name" => "Middle Name",
"last_name" => "Last Name",
"phone" => "Phone");
$radios = array( "New", "Changed");
$submit = "Submit Phone Number";
?>
<html>
<head>
<title>Form 2</title>
<style type='text/css'>
<!--
form {
margin: 1.5em 0 0 0;
padding: 0;
}
.field {padding-bottom: 1em;}
label {
font-weight: bold;
float: left;
width: 20%;
margin-right: 1em;
text-align: right;
}
.submit {
margin-left: 35%;
}
-->
</style>
</head>
<body>
<h3>Please enter your phone number below</h3>
<?php
/* loop that displays the form */
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
foreach($labels as $field => $label)
{
echo "<div class='field'><label for='$field'>$label</label>
<input id='$field' name='$field' type='text' value='".#$$field."'
size='50%' maxlength='65' /></div>\n";
}
echo "<div class='field'>
<input type='radio' name='status' checked='checked'
value='new' style='margin-left: 25%'/>$radios[0]
<input type='radio' name='status'
value='changed' style='margin-left: 1em' />$radios[1]</div>\n";
echo "<div><input type='hidden' name='submitted' value='yes' /></div>\n";
echo "<div class='submit'>
<input type='submit' name='phoneButton' value='$submit'></div>";
?>
</form>
</body>
</html>
... and a php file which checks for blanks or validates the form called (checkBlankOnly2.php)
<?php
/* Program name: checkBlankOnly_2.php
* Description: Program displays the blank form and checks
* all the form fields for blank fields.
*/
if(isset($_POST['submitted']) and $_POST['submitted'] == "yes")
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
if($field != "middle_name")
{
$blank_array[] = $field;
}
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($blank_array) > 0)
{
$message = "<p style='color: red; margin-bottom: 0;
font-weight: bold'>
You didn't fill in one or more required fields.
You must enter:
<ul style='color: red; margin-top: 0;
list-style: none' >";
/* display list of missing information */
foreach($blank_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($good_data);
include("form_test4.inc");
exit();
}
foreach($_POST as $field => $value)
{
if(!empty($value))
{
$name_patt = "/^[A-Za-z' -]{1,50}$/";
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
$radio_patt = "/(new|changed)/";
if(preg_match("/name/i",$field))
{
if(!preg_match($name_patt,$value))
{
$error_array[] = "$value is not a valid name";
}
}
if(preg_match("/phone/i",$field))
{
if(!preg_match($phone_patt,$value))
{
$error_array[] = "$value is not a valid phone number";
}
} // endif phone format check
if(preg_match("/status/i",$field))
{
if(!preg_match($radio_patt,$value))
{
$error_array[] = "$value is not a valid status";
}
}
}
$clean_data[$field] = strip_tags(trim($value));
}
if(#sizeof($error_array) > 0)
{
$message = "<ul style='color: red; list-style: none' >";
foreach($error_array as $value)
{
$message .= "<li>$value</li>";
}
$message .= "</ul>";
echo $message;
extract($clean_data);
include("form_test4.inc");
exit();
}
else
{
echo "Data is all okay";
}
}
else
{
include("form_test4.inc");
}
?>
I can not figure out where my error comes, which I'm certain the problem is with the phone number. My lesson said that the phone number preg_match is for the numbers formats 555-5555 or (888) 555-5555, still when I insert all my data like: first name, last name and phone number in these formats I got the error "not a valid phone number".
Please help me, I can't figure it out.
Thanks.
The field phoneButton is seen as a phone number because it passes your condition if (preg_match("/phone/i",$field)), it's value "Submit Phone Number" then gets validated as a phone number, thus generating the error "Submit Phone Number is not a valid phone number".
Rename your "phoneButton" field to, for example, "submitButton" and you should be fine.
Replace
$phone_patt = "/^[0-9)(xX -]{7,20}$/";
with
$phone_patt = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/";

Categories