I have simple php validation form that is halfway working. If you leave the field empty and click submit, it does the display the correct error message. The issue is with the regular expressions. For example if the currency field is not valid it doesnt display the correct error message. As a matter when clicking submit it reloads the page and erases all the values in the textboxes. How come it will not display the correct error message?
HTML Form
<form action="" method="post" id="form">
<label for="tile">Title: <em>*</em></label>
<input type="text" name="title" id="title" value="<?php echo $form['title']; ?>"> <?php echo $error['title'] ?>
<label for="currency">Currency: <em>*</em></label>
<input type="text" name="currency" id="currency" value="<?php echo $form['currency']; ?>"> <?php echo $error['currency'] ?>
<input type="submit" name="submit" id="submit">
</form>
PHP Validator
//variables
$error_open = "<label class='error'>";
$error_close = "</label>";
$valid_form = TRUE;
$redirect = "success.php";
$form_elements = array('title', 'currency');
$required = array('title', 'currency');
foreach ($required as $require)
{
$error[$require] = '';
}
if (isset($_POST['submit']))
{
//process form
//get form data
foreach ($form_elements as $element)
{
$form[$element] = htmlspecialchars($_POST[$element]);
}
//check form elements
//check required fields
if ($form['title'] == '')
{
$error['title'] = $error_open . "* This field is required" . $error_close;
$valid_form = FALSE;
}
if ($form['currency'] == '')
{
$error['currency'] = $error_open . "* This field is required" . $error_close;
$valid_form = FALSE;
}
//check formatting
if ($error['title'] == '' && !preg_match('/^([A-Za-z0-9_-]+)/', $form['title']))
{
$error['title'] = $error_open . "* Enter a valid descriptive title" . $error_close;
$valid_form = FALSE;
}
if ($error['currency'] == '' && !preg_match('/^\s*[+-]?(\d*\.\d\d)\s*$/', $form['currency']))
{
$error['currency'] = $error_open . " Enter a valid decimal number <br> * Do not include Dollar($) sign <br> * Example: (1.00)" . $error_close;
$valid_form = FALSE;
}
//check for bad data
if (contains_bad_str($form['title']) ||
contains_bad_str($form['currency']))
{
$valid_form = FALSE;
}
if (contains_bad_str($form['title']) ||
contains_bad_str($form['currency']))
{
$valid_form = FALSE;
}
//check if form is valid
if ($valid_form)
{
//redirect
header("Location: " . $redirect);
}
else
{
include('form.php');
}
}
this worked for me.