Hi all,
I have a medium size website that I have been working on for a client which has a simple (at least I thought it was) contact form and a few RegEx validators for the various fields.
Let me just point out that I am very much a newbie to PHP and know next to nothing about it. I bought a book to try and help me learn it but even scanning through the index didn’t provide me with the answer to this problem.
I essentially have a PHP file called ‘contactus.php’ which contains the main contact form script and the HTML code for the form itself and a separate ‘validate.class.php’ file which carries out the data validation on all the fields before posting to an email.
I have managed to get all my fields to validate and post to an email address. However, I have a dropdown selection box for the person’s ‘State’ which I can’t seem to validate. Without validation it will post but the user doesn’t have to select a state which means it can be left blank. It has the following options as a dropdown menu/selection. The validation needs to ensure that the ‘Please select your State’ option is NOT selected when they submit the form. They MUST select from one of the options on the list.
[ol][li]Please select your State[/li]
[li]Australian Capital Territory[/li]
[li]New South Wales[/li]
[li]Northern Territory[/li]
[li]Queensland[/li]
[li]South Australia[/li]
[li]Tasmania[/li]
[li]Victoria[/li]
[li]Western Australia[/li]
[li]Outside Australia[/li][/ol]
Below, I’ve stripped the excess css files so you can just see the form itself in context and how it works.
This is above the in my main ‘contactus.php’ file:
[php]<?php
define(“EMAIL”, “[email protected]”);
if(isset($_POST[‘submit’])) {
include(‘validate.class.php’);
//assign post data to variables
$name = trim($_POST[‘name’]);
$company = trim($_POST[‘company’]);
$email = trim($_POST[‘email’]);
$phone = trim($_POST[‘phone’]);
$state = trim($_POST[‘state’]);
$country = trim($_POST[‘country’]);
$message = trim($_POST[‘message’]);
//start validating our form
$v = new validate();
$v->validateStr($name, “name”, 5, 75);
$v->validateStr($company, “company”, 10, 75);
$v->validateEmail($email, “email”);
$v->validatePhone($phone, “phone”, 10, 16);
$v->validateState($state, “state”, 5, 75);
$v->validateStr($country, “country”, 5, 75);
$v->validateStr($message, “message”, 10, 1500);
if(!$v->hasErrors()) {
$header = “From: $email\n” . “Reply-To: $email\n”;
$subject = “Quote & Print Software - Main Contact Form Enquiry”;
$email_to = EMAIL;
$emailMessage .= "Name: " . $name . “\n”;
$emailMessage .= "Company: " . $company . “\n\n”;
$emailMessage .= "Email: " . $email . “\n”;
$emailMessage .= "Phone: " . $phone . “\n”;
$emailMessage .= "State: " . $state. “\n”;
$emailMessage .= "Country: " . $country . “\n\n”;
$emailMessage .= $message;
//use php's mail function to send the email
@mail($email_to, $subject ,$emailMessage ,$header );
//grab the current url, append ?sent=yes to it and then redirect to that url
$url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header('Location: '.$url."?sent=yes");
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
$nameErr = $v->getError("name");
$companyErr = $v->getError("company");
$emailErr = $v->getError("email");
$phoneErr = $v->getError("phone");
$stateErr = $v->getError("state");
$countryErr = $v->getError("country");
$messageErr = $v->getError("message");
}//end error check
}// end isset
?>[/php]
This is the contact form itself in the of my main php file:
[code]
<?php echo $message_text; ?>
<?php echo $errors; ?>
<?php if(isset($_GET['sent'])): ?>
Full Name:
<?php echo $nameErr; ?>
Company:
<?php echo $companyErr; ?>
<p><label><strong>Email:<span class="requiredfield"> *</span></strong><br />
<input type="text" name="email" class="textfield" value="<?php echo htmlentities($email); ?>" />
</label><br /><span class="errors-desc"><?php echo $emailErr ?></span></p>
<p>
<label><strong>Phone Number:<span class="requiredfield"> *</span></strong><br />
<input type="text" name="phone" class="textfield" onKeyPress="return numbersonly(this, event)" maxlength="16" value="<?php echo htmlentities($phone); ?>" />
</label><br />
<span class="adv_fielddesc">Must be between 10-16 digits incl. area or dialing code (without spaces)</span><br /><span class="errors-desc"><?php echo $phoneErr ?></span></p>
<p>
<label><strong>State:<span class="requiredfield"> *</span></strong><br />
<select name="state" size="1" class="textfield" value="<?php echo htmlentities($state); ?>" style="height:auto;">
<option value="NULL" selected>Please select your State »</option>
<option value="Australian Capital Territory">Australian Capital Territory</option>
<option value="New South Wales">New South Wales</option>
<option value="Northern Territory">Northern Territory</option>
<option value="Queensland">Queensland</option>
<option value="South Australia">South Australia</option>
<option value="Tasmania">Tasmania</option>
<option value="Victoria">Victoria</option>
<option value="Western Australia">Western Australia</option>
<option value="Outside Australia">Outside Australia</option>
</select>
</label><br /><span class="errors-desc"><?php echo $stateErr ?></span>
</p>
<p>
<label><strong>Country:<span class="requiredfield"> *</span></strong><br />
<input type="text" name="country" class="textfield" value="<?php echo htmlentities($country); ?>" />
</label><br /><span class="errors-desc"><?php echo $countryErr; ?></span>
</p>
<p><label><strong>Message:<span class="requiredfield"> *</span></strong><br />
<textarea name="message" class="textarea" cols="45" rows="5"><?php echo htmlentities($message); ?></textarea>
</label><br /><span class="errors-desc"><?php echo $messageErr ?></span></p>
<p><input type="submit" name="submit" class="button" value="Submit" /></p>
</form>
And finally, here is the validate.class.php script which runs the validation on all the fields.
[php]<?php
class validate {
// ---------------------------------------------------------------------------
// paramaters
// ---------------------------------------------------------------------------
/**
- Array to hold the errors
- @access public
-
@var array
*/
public $errors = array();
// ---------------------------------------------------------------------------
// validation methods
// ---------------------------------------------------------------------------
/**
- Validates a string
- @access public
- @param $postVal - the value of the $_POST request
- @param $postName - the name of the form element being validated
- @param $min - minimum string length
- @param $max - maximum string length
-
@return void
*/
public function validateStr($postVal, $postName, $min = 5, $max = 500) {
if(strlen($postVal) < intval($min)) {
$this->setError($postName, ucfirst($postName)." must be at least {$min} characters long.");
} else if(strlen($postVal) > intval($max)) {
$this->setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
}
}// end validateStr
/**
- Validates an email address
- @access public
- @param $emailVal - the value of the $_POST request
- @param $emailName - the name of the email form element being validated
-
@return void
/
public function validateEmail($emailVal, $emailName) {
if(strlen($emailVal) <= 0) {
$this->setError($emailName, “Please enter an Email Address”);
} else if (!preg_match(’^([a-zA-Z0-9]+[.|_|-|£|$|%|&]{0,1})[a-zA-Z0-9]{1}@([a-zA-Z0-9]+[.|_|-|£|$|%|&]{0,1})*([.]{1}([a-zA-Z]{2,4}))$^’, $emailVal)) {
$this->setError($emailName, “Please enter a Valid Email Address”);
}
}// end validateEmail
/**
- Validates phone number
- @access public
- @param $phoneVal - the value of the $_POST request
- @param $phoneName - the name of the phone form element being validated
-
@return void
*/
public function validatePhone($phoneVal, $phoneName) {
if(strlen($phoneVal) <= 0) {
$this->setError($phoneName, “Please enter a Valid Phone Number without spaces”);
} else if (!preg_match(’^[0-9]{10}([0-9]{6})?$^’, $phoneVal)) {
$this->setError($phoneName, “Please enter a Valid Phone Number without spaces”);
}
}// end validatePhone
/**
- Validates State selection box
- @access public
- @param $stateVal - the value of the $_POST request
- @param $stateName - the name of the State dropdown box form element being validated
-
@return void
*/
public function validateState($stateVal, $stateName) {
if (!preg_match(’^([a-zA-Z])$^’, $stateVal)) {
$this->setError($stateName, “Please select your state from the dropdown list”);
}
}// end validateState
// ---------------------------------------------------------------------------
// error handling methods
// ---------------------------------------------------------------------------
/**
- sets an error message for a form element
- @access private
- @param string $element - name of the form element
- @param string $message - error message to be displayed
-
@return void
*/
private function setError($element, $message) {
$this->errors[$element] = $message;
}// end logError
/**
- returns the error of a single form element
- @access public
- @param string $elementName - name of the form element
-
@return string
*/
public function getError($elementName) {
if($this->errors[$elementName]) {
return $this->errors[$elementName];
} else {
return false;
}
}// end getError
/**
- displays the errors as an html un-ordered list
- @access public
-
@return string: A html list of the forms errors
*/
public function displayErrors() {
$errorsList = “<ul class=“errors”>\n”;
foreach($this->errors as $value) {
$errorsList .= “ - ”. $value . “ \n”;
}
$errorsList .= “
return $errorsList;
}// end displayErrors
/**
- returns whether the form has errors
- @access public
-
@return boolean
*/
public function hasErrors() {
if(count($this->errors) > 0) {
return true;
} else {
return false;
}
}// end hasErrors
/**
- returns a string stating how many errors there were
- @access public
-
@return void
*/
public function errorNumMessage() {
if(count($this->errors) > 1) {
$message = “There were " . count($this->errors) . " errors sending your message!\n”;
} else {
$message = “There was an error sending your message!\n”;
}
return $message;
}// end hasErrors
}// end class[/php]
Please keep in mind that I know basically nothing about PHP so I don’t want to change the basic system of validation if at all possible - it would just be too hard.
What I really am looking for help with is the regex. I’ve managed to fudge my way through the rest of the contact form using regex code snippets from the web. I’m just stuck on this one field.
If I have forgotten something or you need more info, please let me know.
Thanks