addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgooglegroupsimageimagesinstagramlinklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1outlookpersonStartprice-ribbonImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruseryahoo

Milwaukee PHP Users Group Message Board MKEPUG Discussion Forum › Help with PHP validation with HTML form

Help with PHP validation with HTML form

Adam S.
user 55402362
Milwaukee, WI
Post #: 1
OK I'm going to begin with that I'm a novice PHP programmer with 3-4 months experience I understand code when I see it in front of me but have difficult time coding what I would "like" to do. Here it goes I'm working on a big project (In my eyes at least) and what I'm going to ask is just a part of the whole project. I'm having trouble with getting form validation to work. The main problem is the data I'm trying to validate is not doing anything I get a blank screen everytime I hit the submit button. I know reason is the code doesn't instantiate any object nor does it process anything or check anything so I'm just not sure what I'm missing from what I have produced so far. Also, I would like to define an array with mandatory fields definition and type/method to check their validity.

Example PHP:
$mandatory_fields['FamilyName'] = 'isAlphabet';
$mandatory_fields['GivenName'] = 'isAlphabet';
so on and so forth....

I would like to foreach the $mandatory_fields instead of going through the tedious task of setting each one. I would also like to do the same idea for an error messages array had just reference the error with an ID. Then create an error handling class to separate the two artifacts (form validation and error handling) to shorten up my code quite a bit. I'll post my code into separate posts since I can't put it all of it in one post lol. If there is a better way to post the code I would like to know I just didn't see an option for loading a file besides the picture or video. I know I'm asking for a lot and I've looked for answers online but I just can't put it into the context of my project. I would greatly appreciate any help and/or advice with my problems.
Adam S.
user 55402362
Milwaukee, WI
Post #: 2
This is my code from the HTML page where my HTML form is located on:
<?php

if(isset($_POST['Submit']))
{
//import the validation library
include('validateForm.php');

$mandatory_fields[] = array($_POST); //checks for required fields
$errors[] = array(); //stores the errors

//Create variables from each HTML form element using POST
$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"]);
$checklegal = trim($_POST["checklegal"]);//r­adio button
$applyPosition = trim($_POST["applyPosition"]);­
$startDate = trim($_POST["startDate"]);
$checkshift = trim($_POST["checkshift"]);//r­adio button
$idealHours = trim($_POST["idealHours"]);
$salaryRange = trim($_POST["salaryRange"]);
$shifttype = trim($_POST["checkshift"]);//r­adio button
$skillsList = trim($_POST["skillsList"]);//t­extarea
$skillsComputer = trim($_POST["skillsComputer"]);­//textarea
$hsName = trim($_POST["hsName"]);
$hsLocation = trim($_POST["hsLocation"]);
$hsPhoneNum = trim($_POST["hsPhoneNum"]);
$hsGrad = trim($_POST["hsGrad"]);//radio­ button
$hsDegree = trim($_POST["hsDegree"]);
$collegeName = trim($_POST["collegeName"]);
$collegeLocation = trim($_POST["collegeLocation"]­);
$collegePhoneNum = trim($_POST["collegePhoneNum"]­);
$collegeGrad = trim($_POST["collegeGrad"]);//­radio button
$collegeDegree = trim($_POST["collegeDegree"]);­
$techName = trim($_POST["techName"]);
$techLocation = trim($_POST["techLocation"]);
$techPhoneNum = trim($_POST["techPhoneNum"]);
$techGrad = trim($_POST["techGrad"]);//rad­io button
$techDegree = trim($_POST["techDegree"]);
//There are four fieldsets for employment history
$OrganizationName = trim($_POST["OrganizationName"­]);
$companyLocation = trim($_POST["companyLocation"]­);
$Telephone = trim($_POST["Telephone"]);
$FormattedName = trim($_POST["FormattedName"]);­
$leavingReason = trim($_POST["leavingReason"]);­
$Title = trim($_POST["Title"]);
$EndDate = trim($_POST["EndDate"]);
$Compensation = trim($_POST["Compensation"]);
$SalaryOptions = trim($_POST["SalaryOptions"]);­
$tempEmploy = trim($_POST["tempEmploy"]);//r­adio button
$tempEmplyDate = trim($_POST["tempEmplyDate"]);­
$unemployReason = trim($_POST["unemployReason"]);­
$applicantName = trim($_POST["applicantName"]);­
$applicantSignName = trim($_POST["applicantSignName"­]);
$signDate = trim($_POST["signDate"]);

//Standard form fields
$mandatory_fields['FamilyName'] = 'isAlphabet';
$mandatory_fields['GivenName'] = 'isAlphabet';
$mandatory_fields['MiddleInitial'] = 'isAlphabet';
$mandatory_fields['curAddress'] = 'validateAddress';
$mandatory_fields['Municipality'] = 'isAlphabet';


/*foreach ($_POST as $key => $value) {
if(in_array($key, $mandatory_fields) && empty($value)) {
$errors = "" .$key. ""\n;
}
}

*/
//start validating our form
$v = new validateForm();
$v->isAlphabet($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 false;
}
}
?>

I would like to foreach the POST variables (if pausible) instead of listing each one like I did.
Adam S.
user 55402362
Milwaukee, WI
Post #: 3
Here is the code for the PHP validation page that contains my classes and functions:
<?php
class validateForm {

//------------------------------------­------------------------------
// validation methods
//------------------------------------­------------------------------

/**
* Validates alphabet fields
*
*@access public
*@param
*/
public function isAlphabet($element) {
if(strlen($element) <= 0) {
$this->setError($element, "Please enter something into the text field.");
}
else if(preg_match("/^[a-zA-Z\\-\\., \']+$/")) {
$this->setError($element, "This field must consist only of letters A-Z, ' and - .");
}
else
{
return true;
}
}

public function isDate($element) {
if(strlen($element) <= 0) {
$this->setError($element, "Please enter a date in the format mm/yy.");
}
else if(preg_match("/^([0-9]{2})/([0-9]{­2})+$/")) {
$this->setError($element, "Field must only contain numbers.");
}
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;
}
}
/*public function isDate() {
if(strlen($element

/*
$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($element, $errors){
$this->errors[$element] = $errors;
}//end logError

/**
* returns the error of a single form element
*
* @access public
* @param string $element - name of the form element
* @return string
*/
public function getError($element){
if($this->errors[$element]){
return $this->errors[$element];
}
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(){
$errors = "<ul class=\"errors\">\n";
foreach($this->errors as $value) {
$errors .= "<li>". $value . "</li>\n";
}
$errors .= "<\ul>\n";
return $errors;
}//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
}
?>

I know my code is mostly likely incomplete and messy I'm just doing my coding on what I know
Adam S.
user 55402362
Milwaukee, WI
Post #: 4
I would post the HTML page but its to many characters long then what is allowed but feel free to contact me at my email if you have any questions.
Aaron S.
aaronsaray
Milwaukee, WI
Post #: 75
Really the first thing you have to know is that you get a 'blank screen' because you're getting a PHP error. Your best thing to do next is to enable error reporting to the screen in PHP.

You can do this by editing the php.ini file to have display_errors directive on. If you don't have access to that, you can call ini_set() followed by that.

Check this url: http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors­

Once you get that, run the script again, and note the error. That may be easier for us to help :)
Adam S.
user 55402362
Milwaukee, WI
Post #: 5
Well I checked my display_errors and its turned on because I was getting errors before I started getting the blank screen issue. I'm thinking the code is quietly ending itself based on the reason I'm not passing data anymore if I was I should get an error? The log_errors is working fine also and no errors pop up there. I also created an foreach function template to dump the form array data which defines the mandatory fields and what I want to validate it but I'm a little lost on the logic part.

/*
* $req_fields is defining which fields is mandatory and the method you want to use to validate it.
*
*
*
*/
var_dump($_POST);
foreach($_POST as $index_POST => $one_POST) {
if(isset($req_fields[$index_POST])) {
$le_method = $req_fields[$index_POST];
$le_method($one_POST);
}
}

le_method I know I need to use my form validation just not sure how to call it. The index_part I believe takes all the $_Post variables and puts into an array named $index then $one_POST I get confused.
Art J.
user 11886601
Plymouth, WI
Post #: 13
Adam,
I am a novice PHP programmer myself, what is great about learning a new language is you "rediscover" all the lessons you learned from your previous language that you are an expert in. You have a lot to look at, so I would copy your existing code in a new php file and start deleting. Use only 1 field and forget about valididating but making sure you are able to post a variable from form to server. Then try validating that one field. Your code sample is too big for people to see through the "noise". I find by "rediscovering" baby steps, I find the differences that PHP has compared to my reference language.
Beth Tucker L.
e3betht
Verona, WI
Post #: 22
If you are not getting an error message, it's possible that the error is in one of your included files instead of in the main file. Have you tried loading your validation file separately and see if you generate a PHP error that way?
Aaron S.
aaronsaray
Milwaukee, WI
Post #: 77
I would agree with Art - start trimming down your PHP - and verify each line that worked. Sometimes we get soo much going on and then we have a hard time tracking down where it is.
Powered by mvnForum

Our Sponsors

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy