LOL! Thanks for the help, Bunkermaster, I get the idea of what needs to be done. Now the fun part is I'll just have to figure out the coding syntax and structure to make it work properly LOL.
Complex HTML form and using PHP to validate all fields...
We were all at that point one day (circa 1999 for me) and that's where the fun starts indeed. We're here to help you along the way if needed.
Use the source Luke!
OK I tried testing my code and when I hit the submit button it goes from my employment application page to my validation page but then it goes completely blank??? I'm figuring that I either need to put my code all in the HTML form page so it re-submits back to itself. Or I need to set-up a <div> element to display my errors (not sure if I set it up properly though). Or my error array is not functioning properly. Or its most likely something I don't have a clue on (I'm going with option 4:p).
Code from employment form:
<?php
if(isset($_POST['submit']))
{
//import the validation library
include('validateForm.php');
$mandatory_fields[] = array(); //stores the validation rules
$errors[] = array(); //stores the errors
//Create post data to variables from each HTML form element
$FamilyName = trim($_POST["FamilyName"]);
$GivenName = trim($_POST["GivenName"]);
$MiddleInitial = trim($_POST["MiddleInitial"]);
$curAddress = trim($_POST["curAddress"]);
$Municipality = trim($_POST["Municipality"]);
$Region = trim($_POST["Region"]);
$PostalCode = trim($_POST["PostalCode"]);
$phoneNumber = trim($_POST["phoneNumber"]);
$EmailAddress = trim($_POST["EmailAddress"]);
$legalYes = trim($_POST["legalYes"]);//radio button
$legalNo = trim($_POST["legalNo"]);//radio button
//cut out the other post variables to save space for posting.....
//Standard form fields
$mandatory_fields['FamilyName'] = 'isAlphabet';
$mandatory_fields['GivenName'] = 'isAlphabet';
$mandatory_fields['MiddleInitial'] = 'isAlphabet';
$mandatory_fields['curAddress'] = 'validateAddress';
/*foreach ($_POST as $fieldname => $value) {
if(isset($_POST['fieldname'])) {
}
}
*/
//start validating our form
$v = new validateForm();
$v->isAlphabet($FamilyName, "FamilyName");
//Counts up all the errors
if (!$v->hasErrors()) {
//Sets the number of errors
$message = $v->errorNumMessage();
//Store the errors list in a variable
$errors = $v->displayErrors();
//Get the individual error messages
$FamilyName = $v->getError("FamilyName");
}
else
{
return true;
}
}
?>
Code from PHP validation page:
<?php
class validateForm {
//------------------------------------------------------------------
// validation methods
//------------------------------------------------------------------
/**
* Validates alphabet fields
*
*@access public
*@param
*/
public function isAlphabet($elementName) {
if(strlen($elementName) <= 0) {
$this->setError($elementName, "Please enter something into the text field.");
}
else if(preg_match("/^[a-zA-Z\\-\\., \']+$/")) {
$this->setError($elementName, "This field must consist only of letters A-Z, ' and - .");
}
else
{
return true;
}
}
/*function validateAddress($curAddress){
if(strlen($curAddress) <= 0 || strlen($curAddress) >= 50) {
$this->setError($curAddress, "Please enter address and must be no longer than 50 characters");
}
else if(preg_match("/^[a-zA-Z0-9 -.,:']+$/")) {
$this->setError("Address can only consist of letters A-Z, numbers 0-9, spaces, - , ",", :, and '.");
}
else
{
return true;
}
}
function validateZipcode($PostalCode){
if(strlen($PostalCode) <= 0 || strlen($PostalCode) >= 8) {
$this->setErrors($PostalCode, "Please enter a zip code in and can only be a max of 8 characters.");
}
else if(preg_match("/^([0-9]{5})(-[0-9]{4})?$/i")){
$this->setErrors("Zip code can only contain numbers with the format of xxxxx or xxxxx-xxxx");
}
else
{
return true;
}
}
public function validateEmail($EmailAddress){
if(strlen($EmailAddress) <= 0) {
$this->setError($EmailAddress, "Please enter in an email address");
}
else if(preg_match("/^\S+@[w\d.-]{2,}\.[\w]{2,6}$/iU")){
$this->setError($EmailAddress, "Please enter in a valid email address");
}
else
{
return true;
}
}
function validatePhoneNum($phoneNumber){
if(strlen($phoneNumber) <= 0 || strlen($phoneNumber) >= 10){
$this->setErrors($phoneNumber, "Please enter a phone number that can only be a max of 10 characters long.";
}
else if(!preg_match("/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/s")){
$this->setErrors($phoneNumber, "Please enter a valid phone number.");
}
else
{
return true;
}
}
$query = sprintf("INSERT INTO tbl (FamilyName, GivenName) Values (%s, %s)",
mysqli_real_escape_string($link, $FamilyName),
mysqli_real_escape_string($link, $GivenName)
);
*/
//---------------------------------------------------------
// 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($elementName, $errors){
$this->errors[$elementName] = $errors;
}//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 .= "<li>". $value . "</li>\n";
}
$errorsList .= "<\ul>\n";
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 are " . count($this->errors) . " errors in the form!\n";
}
else
{
return true;
}
}//end errorNumMessage
}//end validateForm class
exit;
?>
@ On the mandatory_fields array and creating a foreach statement to handle each variable I'm not sure how to go about coding it syntax-wise but I decided to do it the long way so that I can at least test out my validation functions to see that they're working properly. I found a decent example of the concept you mentioned but it was different in certain ways (PHP example: https://github.com/benkeen/php_validation).
InsideVoid;11008903 wrote:then it goes completely blank???
Sounds like there were no errors in the form data you sent then. After all, you're not telling PHP to do anything if that's the case:
//Counts up all the errors
if (!$v->hasErrors()) {
//brad: ...
}
else
{
return true; //brad: in other words, don't output anything - just quit silently
}
@ Well i tried to change the true to false and still got a blank page and I'm completely lost on what is wrong. I think I have to call one of the other error functions but I'm not sure how or which one to be honest?
InsideVoid;11008939 wrote:Well i tried to change the true to false and still got a blank page
Again, that should be as expected. It doesn't matter what value you return - true, false, or the string "I like watermelons." What matters is that you're telling PHP to stop executing the current script at that point. Since you haven't outputted any data (or any redirect headers, or... well, anything), you shouldn't expect to receive any data on the other end.
OK i get its not outputting anything now the question is how do I fix it??? I'm not sure what to do and I can't find anything on the internet to help me out besides asking people in forums.
From the code you posted up there, the validation page does nothing. It's just the declaration of a class and the exit command.
Maybe if you asked it to do something... It's do it?
InsideVoid;11008951 wrote:OK i get its not outputting anything now the question is how do I fix it???
What do you want it to do instead of outputting nothing?
I would like to count out the number of errors and then display these errors to the end user with the corresponding error message telling them what type of error they have and having them fix it. I was thinking of putting these error messages in a <div> above the form which asks them to fill in any empty fields, put in the correct data types in the right fields, so and so forth. I would like the form to repopulate the correct fields so the user doesn't have to fill out the form all over again and just fix their errors. Then once all the errors are fixed then the form would next parse the form data into a XML gateway to be sent to the database. I'm just more worried about the validation first before I worry about the next step.
Thanks,
A novice PHP programmer
InsideVoid, the validation page as it is is just declaration. The code doesn't instantiate any object nor does it process anything or check anything. You probably need to instantiate your class and call some methods?
I understand that what you guys are saying the problem is I'm not sure on how to code it or what functions to use and/or create to do what I'm wanting to do for my situation :-(. I've looked online for how to instantiate a class but I'm confused on how to do it in the context of my project. But I still have the problem on creating a foreach loop for the values of my POST variables inputted by the user and putting them into an array. Then creating a foreach loop for the mandatory fields array and an error message array and calling these error messages by IDs. Then creating an error handling class to separate the form validation from the error handling that Bunkermaster suggested. All this is confusing me greatly and looking at examples online haven't helped but create more questions and confusion.
InsideVoid I suggest you start easy with the following for your validation page:
var_dump( $_POST );
Then you start adding logic to that script:
var_dump( $_POST );
foreach($_POST as $index_POST => $one_POST){
if( isset( $reference_array[$index_POST] ) ){
$le_method = $reference_array[$index_POST];
$le_method( $one_POST );
}
}
$reference_array being, of course, your array defining which field is mandatory and the method you want to use to control its content. This should give you a kick start. If you need more assistance, I'll try to guide you but you need to do it yourself as forum is what this place is all about.
@ - Thank you for the help
The code you provided is exactly what I was thinking of in theory just couldn't figure out the correct syntax and structure. My code that I came up with was no where near your code LOL. Now I'll do my best to connect the dots