Jump to content

User input validation eith regular expressions


Go to solution Solved by Ch0cu3r,

Recommended Posts

I wish to implement regular expressions as a way to check user input and so far i came up with code below. When i run my script, and input numbers for first and last names, they get posted successfully regardless of my regex and i get this error Notice: "Undefined index: last_name in......." and "Undefined index: first_name in.......". I was wondering what i may be doing wrong.

<?php 
$errors = array();
// .....create database connection......//
if (isset($_POST['insert'])) {
$last_name = trim($_POST['last_name']);
$first_name = trim($_POST['first_name']);
  // initialize flag
  $OK = false;
  // initialize prepared statement
  $stmt = $conn->stmt_init();
  // create SQL
  $sql = 'INSERT INTO voter_tracking (
			v_id,
			last_name,
			first_name)
		VALUES(?, ?)';
  if ($stmt->prepare($sql)) {
	// bind parameters and execute statement
	$stmt->bind_param('iss', $_POST['v_id'], $_POST['last_name'], $_POST['first_name']);
    // execute and get number of affected rows
	$stmt->execute();
	if ($stmt->affected_rows > 0) {
	  $OK = true;
	}
  }
  // redirect if successful or display error
  if ($OK) {
	echo 'posted';
	exit;
  } else {
	$error = $stmt->error;
  }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
	<div id="main">
		<fieldset>
				<legend><h2>Add New Voter Record:</h2></legend>
				<?php if (isset($error)) {
				  echo "<p class=\"warning\">Error: $error</p>";
				} ?>
			<form id="form1" method="post" action="">			  
			  <p>
				<label for="last_name">Last Name:</label>
				<?php // Full Name must contain letters, dashes and spaces only and must start with upper case letter.
					if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["last_name"]) === 0)
					$errName = '<p class="errText">Last Name must be from letters, dashes, spaces and must not start with dash</p>';?>
				<input type="text" name="last_name" class="widebox" id="name" required aria-required="true">
			  </p>
			  <p>
				<label for="first_name">First Name:</label>
				<?php // Full Name must contain letters, dashes and spaces only and must start with upper case letter.
					if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["first_name"]) === 0)
					$errName = '<p class="errText">Last Name must be from letters, dashes, spaces and must not start with dash</p>';?>
				<input type="text" name="first_name" class="widebox" required aria-required="true">
			  </p>

			  <p>
				<input type="submit" name="insert" value="Insert New Entry" id="insert">
			  </p>

			</form>
		</fieldset>  		 
	</div>
</body>
</html>

  • Solution

 

When i run my script, and input numbers for first and last names, they get posted successfully regardless of my regex

Because you are inserting the record before you verify the users input. You need to first verify the input, and then insert the record if it passes your requirements

 

 

i get this error Notice: "Undefined index: last_name in......." and "Undefined index: first_name in......."

$_POST["last_name"] and $_POST["first_name"] wont exist until the form is submitted. You are not checking to see if they exist before you used preg_match.

 

I have rearranged your code, so the user input is verified first, and a record is inserted when the input pass your requirements

<?php

$errors = array();
// .....create database connection......//
if (isset($_POST['insert']))
{
    $last_name  = trim($_POST['last_name']);
    $first_name = trim($_POST['first_name']);

    // verify users input
    // check last_name field
    if(!preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["last_name"]))
    {
        // set error for last_name field
        $errors['last_name'] = '<p class="errText">Last Name must be from letters, dashes, spaces and must not start with dash</p>';
    }

    // check first_name field
    if(!preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST["first_name"]))
    {
        // set error for first_name field
        $errors['first_name'] = '<p class="errText">First Name must be from letters, dashes, spaces and must not start with dash</p>';
    }

    // if no errors are set, inset record into database
    if(empty($errors))
    {
        // initialize flag
        $OK = false;

        // initialize prepared statement
        $stmt = $conn->stmt_init();
        // create SQL
        $sql = 'INSERT INTO voter_tracking (
                v_id,
                last_name,
                first_name)
            VALUES(?, ?)';
        
        if ($stmt->prepare($sql))
        {
            // bind parameters and execute statement
            $stmt->bind_param('iss', $_POST['v_id'], $_POST['last_name'], $_POST['first_name']);
            // execute and get number of affected rows
            $stmt->execute();
            if ($stmt->affected_rows > 0)
              $OK = true;
        }

        // redirect if successful or display error
        if ($OK)
        {
            echo 'posted';
            exit;
        }
        else
            $error = $stmt->error;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
    <div id="main">
        <fieldset>
                <legend><h2>Add New Voter Record:</h2></legend>
                <?php if (isset($error)) {
                  echo "<p class=\"warning\">Error: $error</p>";
                } ?>
            <form id="form1" method="post" action="">             
              <p>
                <label for="last_name">Last Name:</label>
                <?php
                // ouput error for last_name field
                if(isset($errors['last_name'])) echo $error['last_name'];
                ?>                    
                <input type="text" name="last_name" class="widebox" id="name" required aria-required="true">
              </p>
              <p>
                <label for="first_name">First Name:</label>
                <?php
                // ouput error for first_name field
                if(isset($errors['first_name'])) echo $error['first_name'];
                ?>  
                <input type="text" name="first_name" class="widebox" required aria-required="true">
              </p>

              <p>
                <input type="submit" name="insert" value="Insert New Entry" id="insert">
              </p>

            </form>
        </fieldset>          
    </div>
</body>
</html>
Edited by Ch0cu3r
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.