Jump to content

PHP Validation


laarchie

Recommended Posts

Chaps, as a beginner developing his first web app in PHP, I have done fairly well.

 

However, I am struggling when it comes to validation.

 

I have written different ELSEIF statements as seen below which would actually carry out the validation itself.

// First name must be filled and in correct format.

if(empty($FirstName)) {
    $errFirstName = '<p class="errText"> Please enter a value</p>';
    echo $errFirstName;
}elseif(!preg_match('/^[a-z]+$/i',$FirstName)){
    $errFirstName = '<p class="errText">Name may not start with a dash. Letters, spaces and dashes are accepted.</p>';
    echo $errFirstName;
}

The problem is that I do not know how to make them "pop up" when the user makes a mistake.

 

I have a form in addteam.php seen below:

<form action="pushteam.php" method="post">
            <p>Team name: <input type="text" name="TeamName" /></p>
            <p>Description: </p>
            <p><textarea name="Description" rows="4" cols="50">Add your description here.</textarea></p>
            <p><input type="submit"/></p>
          </form>

And a pushplayer.php script that pushes it to a mysql database:

// Get values from form
  $TeamName=$_POST['TeamName'];
  $Description=$_POST['Description'];


  }

  // Insert data into database
  $sql="INSERT INTO Teams(TeamName, Description)VALUES('$TeamName', '$Description')";
  $result=mysql_query($sql);

  //If successful return to success.php else print error
  if($result){
    header( 'Location: success.php');
  }

  else {
    header( 'Location: failure.php');
  }

The scripts function properly. I would really appreciate if someone could guide me in the right direction here. Make the error pop up and make sure the data is not input. At the moment, if I add my ELSEIF statements, it will carry on and insert the data anyway and redirect me. Thanks

Link to comment
Share on other sites

Usually something like this works fairly well:

$errors = array();

if(empty($FirstName)) {
$errors['FirstName'] = '<p class="errText"> Please enter a value</p>';
}elseif(!preg_match('/^[a-z]+$/i',$FirstName)){
$errors['FirstName'] = '<p class="errText">Name may not start with a dash. Letters, spaces and dashes are accepted.</p>';
}

// after validation...
if (empty($errors)) {
// there were no errors, carry on...
// SQL inserts here...
} else {
// there was errors! display the form again and show errors
}
Link to comment
Share on other sites

Usually something like this works fairly well:

$errors = array();

if(empty($FirstName)) {
    $errors['FirstName'] = '<p class="errText"> Please enter a value</p>';
}elseif(!preg_match('/^[a-z]+$/i',$FirstName)){
    $errors['FirstName'] = '<p class="errText">Name may not start with a dash. Letters, spaces and dashes are accepted.</p>';
}

// after validation...
if (empty($errors)) {
    // there were no errors, carry on...
    // SQL inserts here...
} else {
    // there was errors! display the form again and show errors
}

Thanks for the prompt reply. That makes sense. However, how would I go about displaying the form again?

Link to comment
Share on other sites

 

Thanks for the prompt reply. That makes sense. However, how would I go about displaying the form again?

 

There are many ways to do that. I typically make the form a separate file then have a single 'controller' page that is always called. That page determines if the form will be displayed (initial request for the form or there were errors) or if the form passed validations and should be processed.

 

Here is a simple example: contactform.php (this is the controller page that would be user facing, i.e. requested via the browser)

 

<?php
//Set variable to hold any validation errors
$errors = array();
 
//Check if form was POSTed
if($_SERVER['REQUEST_METHOD']=='POST')
{
    //Perform validation logic
    //If there are any errors append them to the array $errors
 
    //Check if there were any validation errors
    if(!count($errors))
    {
        //Perform additional processing logic, e.g. inserting into DB
        //Errors can occur at this stage as well, if so append to the $errors array
    }
 
    //Verify if all validation and processing succeeded
    if(!count($errors))
    {
        //Redirect user to a success page using a header() redirect
        //This has the added benefit of clearing the $_POST values to prevent double submissions with a page refresh
       header("Location: success.php");
    }
}
 
//Include form. If the form was posted and there were no errors, this logic would not be run
include('mycontactform.php');
Link to comment
Share on other sites

 

There are many ways to do that. I typically make the form a separate file then have a single 'controller' page that is always called. That page determines if the form will be displayed (initial request for the form or there were errors) or if the form passed validations and should be processed.

 

Here is a simple example: contactform.php (this is the controller page that would be user facing, i.e. requested via the browser)

<?php
//Set variable to hold any validation errors
$errors = array();
 
//Check if form was POSTed
if($_SERVER['REQUEST_METHOD']=='POST')
{
    //Perform validation logic
    //If there are any errors append them to the array $errors
 
    //Check if there were any validation errors
    if(!count($errors))
    {
        //Perform additional processing logic, e.g. inserting into DB
        //Errors can occur at this stage as well, if so append to the $errors array
    }
 
    //Verify if all validation and processing succeeded
    if(!count($errors))
    {
        //Redirect user to a success page using a header() redirect
        //This has the added benefit of clearing the $_POST values to prevent double submissions with a page refresh
       header("Location: success.php");
    }
}
 
//Include form. If the form was posted and there were no errors, this logic would not be run
include('mycontactform.php');

I guess I would have to include the form before that script?

Link to comment
Share on other sites

I guess I would have to include the form before that script?

 

It's PHP doesn't really matter where you include it, before or after, as long as you fetch the functions you need first.

 

@Psycho, I also use $_SERVER['REQUEST_METHOD']=='POST'  l for checking form submit, due to IE 10 and below's enter-pressing-submit problem.

I even wrote a function for it:

// Check whether the user
// has clicked the submit
// button in a form.
// The reason we are not simply 
// using if(isset($_POST(GET)['SUBMIT_BUTTON'])) 
// is because it would not work on IE 10 - 
// when the user would press enter
// instead of the button.
	
	function submit_pressed($method){
		$method = strtoupper($method);
			if ($_SERVER['REQUEST_METHOD'] == $method) {
				return true;
			}
		return false;
	}
Link to comment
Share on other sites

I guess I would have to include the form before that script?

 

No. The very last line in that script will include the form. You point the user to this script - not the form. The file with the form would not be directly accessed, only included in the script above.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.