Jump to content

Trying to validate name


codybiggs

Recommended Posts

So I have a form that wants inputs for a kids name, their parents name, email, phone number, and check lists for workshops they can take. I have finished the form...I still need to add the css but I wont to get the validation done first, but my echo wont work once the form is submitted, and there is no name for the kid. it should just go to the validation page and say "you forgot to enter your name" but it goes to the page without showing the echo even though the input is blank. 

 

 

Here is what I have

<!DOCTYPE html>
<html>
<head>
	<title>Program 2</title>
	<link rel="stylesheet" type="text/css" href="BiggsCProgram1.css">
</head>
<body>
<h1>Weather Wizard Workshops</h1>
<p>we host weather wizard workshops throughout the year for kids from 6-12</p>
<P>Please note the following workshops are free to members:</p>
	<ul>
		<li>Make a rain gauge</li>
		<li>Make a Thermometer</li>
	</ul>
	<form action="checkform.php" method="post">
		<fieldset>
			<legend>Register your interests</legend>
			 <input type="checkbox" name="workshop">Make a rain gauge</input>
			 <br>
			 <input type="checkbox" name="workshop">Make a thermometer</input>
			 <br>
			 <input type="checkbox" name="workshop">Make a windsock</input>
			 <br>
			 <input type="checkbox" name="workshop">Make lightning in your mouth</input>
			 <br>
			 <input type="checkbox" name="workshop">Make a Hygrometer</input>
			 <br><br>
			 
			 Your Name:<br>
			<input type="text" name="kids_name">
			<br><br>
			
			Your parent or Guardian's name:<br>
			<input type="text" name="parent_name">
			<br><br>
			
			Your parent or Guardian's E-mail:<br>
			<input type="email" name="email">
			<br><br>
			
			Your parent or Guardian's Phone Number:<br>
			<input type="text" name="phone_number">
			<br><br>
			
			Your Closest Center:		<select>
											<option>Charleston</option>
											<option>Summerville</option>
											<option>Mt.Pleasant</option>
											</select>
											<br><br>
			
			Are you a member?			<input type="radio" name="member"> No</input>
										<input type="radio" name="member"> Yes</input>
										<input type="radio" name="member"> Sign Me Up</input>
										<br><br>
										
			<input type="submit" value="Submit">
			</fieldset>
			</form>
			</body>
			</html>
			 
<!DOCTYPE html>
<html>
<head>
	<title>Check Form</title>
</head>
<body>
<h1>Weather Wizards Regitration Verification Form</h1>
<?php
	if(!empty($_REQUEST['kids_name'])) {
		$kidsName = $_REQUEST['kids_name'];
	}else {
                 $kidsName = NULL;
		echo 'You forgot to enter your name!';

?> 
Link to comment
Share on other sites

unless you cut off some of the php code when you posted it, you are missing a closing } and would be getting a php parse/syntax error, assuming you have set php's error_reporting to E_ALL and display_errors to ON, in the php.ini on your development system (you cannot set these via php statements in your main code and have them show parse/syntax errors in the same code since your code never runs when there is a parse/syntax error.)

 

you should also use $_POST, not $_REQUEST, and your post method form processing code should be near the top of your file, before the start of your html document.

Link to comment
Share on other sites

When checking to see if a value was entered for a field you should ALWAYS trim the field (unless there is a very specific reason why spaces or other white-space characters are an acceptable input). Otherwise, a user can enter only spaces into a text field and be counted as valid input.

 

the empty() function will also return true if the value is the string "0". For a name input I would think that is not a valid value, and treating it as no input would be fine for such and edge case, but you need to keep that in mind when using it to validate input. After trimming the input using strlen() or even if($input=='') would be a more deterministic test of an empty value.

Link to comment
Share on other sites

Cool! This is my first experience with php, so obviously there is a lot to learn. I did have a question though when they leave a input blank I want another echo to show up that says "Weather Wizard, we need your name and your parent or guardian's name, email, phone and your membership status to send information about our workshops. Hit the back button on the browser and try again." Right now I have it set up on every input validation, so if they leave 2 inputs blank then the message shows up twice. Basically if one or more inputs are left blank I want the message to show up only once, not once for each input.

 

Not looking for straight code..just a little bump in the right direction

Link to comment
Share on other sites

I would not recommend telling the user to click the Back button. The application should provide a means to get the user to where they need to go.

 

Here is the process I would recommend:

On the processing script, create an "errors" variable at the top of the script. Then perform validations for each fo the fields and append each error to the error variable. Once all validations have been completed, if there are no errors then proceed with the action you will take with the data (save to the database, send an email, etc.) However, if the errors variable has an values, then re-display the form with the values the user entered previously with applicable error messages for them to address.

 

Here is a very basic example

 

<?php
 
//Create variables for each form input value
//based on form submission else set to default
$name = (isset($_POST['name'])) ? trim($_POST['name']) : '';
$phone = (isset($_POST['phone'])) ? trim($_POST['phone']) : '';
$email = (isset($_POST['email'])) ? trim($_POST['email']) : '';
//Set error message variable
$errorMessage = '';
 
//Check if form was submitted
if($_SERVER['REQUEST_METHOD']=='POST')
{
    //Form was posted perform validations
    //Create variable to hod errors
    $errors = array();
    
    //Validate name
    if($name=='')
    {
        $errors[] = "Name is required";
    }
    //Validate email
    if($email=='')
    {
        $errors[] = "Email is required";
    }
    elseif(!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        $errors[] = "Email is invalid";
    }
    
    //Check if there were errors
    if(!count($errors))
    {
        //Take action on the data and perform a redirect to a 'success' page and
        //exit. The redirect will prevent a resubmission if page is refreshed
        exit();
    }
    
    //There were errors, create message
    $errorMessage = "The following errors occured:";
    $errorMessage .= "<ul><li>" . implode("</li><li>", $errors) . "</li></ul>";
}
?>
<html>
<head></head>
<body>
<h1>Enter your data</h1>
<div class="error"><?=$errorMessage?></div>
<form action="" method="post">
  Name: <input type="text" name="name" value="<?=$name?>"><br>
  Phone: <input type="text" name="phone" value="<?=$phone?>"><br>
  Email: <input type="text" name="email" value="<?=$email?>"><br>
  <button type="submit">Submit</button>
</form>
 
</body>
</html>
Link to comment
Share on other sites

Before you jump to PHP, you should learn to write valid, semantic HTML markup. Mainstream browsers are fairly robust and will render almost anything, but that doesn't mean errors are fine. They can still cause major usability problems.

  • Always validate your markup before you publish it.
  • Void elements like <input> cannot have content or an end tag. They consist of a single start tag. When you're not sure how an element works, use a reference like the Mozilla Developer Network.
  • Don't abuse <br> elements for layout purposes. Styling is done with CSS only.
  • Use the proper input types instead of the generic text type, and mark required fields with the required attribute. This allows the browser to immediately validate the field and assist the user. You still need server-side validation, but wrong input should be caught as early as possible.
  • Use <label> elements to bind input labels to <input> elements.

The code has problems as well.

  • All values must be HTML-escaped before they're inserted into an HTML context. The only exception is when you explicitly want to insert (safe) markup.
  • Treating missing parameters like empty values is a bad idea. When an expected parameter isn't present at all, there's something seriously wrong. Either there's a server-side problem with the form, or the client is broken. This needs to be reported and should also be logged.
  • It's also bad to respond with a “200 OK” status code when the request is not OK. The average human user may be able to deduce this information from the error messages, but that's no excuse for poor usability.
<?php

// collect error messages
$errors = [];

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $expected_params = ['name', 'email'];

    // if a parameter is missing entirely, something is wrong; display an error message, log the error and set an
    // appropriate status code
    foreach ($expected_params as $param)
    {
        if (!isset($_POST[$param]))
        {
            echo 'Missing POST parameter: '.html_escape($param, 'UTF-8');    // feel free to show a pretty error page instead
            trigger_error('Missing POST parameter: '.$param, E_USER_NOTICE);
            http_response_code(HTTP_STATUS_BAD_REQUEST);
            exit;
        }
    }

    if ($_POST['name'] == '')
    {
        $errors['name'] = 'Please enter your name.';
    }

    if ($_POST['email'] == '')
    {
        $errors['email'] = 'Please enter your e-mail address.';
    }

    // if everything is fine, process the input; otherwise set the appropriate HTTP error code
    if (!$errors)
    {
        echo 'OK';
        exit;
    }
    else
    {
        http_response_code(HTTP_STATUS_BAD_REQUEST);
    }
}

?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Title</title>
    </head>
    <body>
        <form method="post">
            <?php if (isset($errors['name'])): ?>
                <em class="error"><?= html_escape($errors['name'], 'UTF-8') ?></em>
            <?php endif; ?>
            <label>Name: <input type="text" name="name" required></label>
            <?php if (isset($errors['email'])): ?>
                <em class="error"><?= html_escape($errors['email'], 'UTF-8') ?></em>
            <?php endif; ?>
            <label>E-mail address: <input type="email" name="email" required></label>
            <input type="submit">
        </form>
    </body>
</html>
<?php

function html_escape($raw_input, $encoding)
{
    return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE, $encoding);
}
<?php

const HTTP_STATUS_BAD_REQUEST = 400;
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.