I have been trying too use PHP to validate my form. The form asks users to enter details which will then get entered into a table in a database once the form has been validated. I have a first name field in the form and I am trying to validate it to make sure that it has a value entered (compulsory field) and should only contain alphabetic characters or a hyphen(-) character.
Here is what i have so far:
<?php
if (isset($_POST["submit"])) {
$flag = false;
$badchar = "";
$string = $_POST["fname"];
$string = trim($string);
$length = strlen($string);
$strmsg = "";
if ($length == 0) {
$strmsg = '<span class="error"> Please enter your first name</span>';
$flag = true;}
else {
for ($i=0; $i<$length;$i++){
$c = strtolower(substr($string, $i, 1));
if (strpos("abcdefghijklmnopqrstuvwxyz-", $c) == false){
$badchar .=$c;
$flag = true;
}
}
if ($flag) {
$strmsg = '<span class="error"> The field contained the following invalid characters: $badchar</span>';}
}
if (!$flag) {
$strmsg = '<span class="error"> Correct!</span>';}
}
?>
<h1>Customer Information Collection <br /></h1>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="custinfo" >
<table>
<tr>
<td><label for="custid">Customer ID (integer value): </label></td>
<td><input type="text" id="custid" name="custid" value="<?php echo $temp ?>" size=11 /><?php echo $msg; ?></td>
</tr>
<tr>
<td><label for="customerfname">Customer First Name: </label></td>
<td><input type="text" id="fname" name="fname" size=50/><?php echo $strmsg; ?></td>
</tr>
The problem I am having is that when I enter a correct string (e.g. John) it still gives me the error "The field contained the following invalid characters: $badchar", also when an incorrect character is entered i would like for it to display the incorrect character in the place of $badchar in the error message but instead it just displays "The field contained the following invalid characters: $badchar".Is there a way to do that?
Any help with these problems would be really appreciated.