简体   繁体   中英

Validating user input with regular expressions

I wish to implement regular expressions as a way to check user input and after reviewing this post ( Issue on Using Regular Expression in PHP Simple Validation ) 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 . I was wondering what i may be doing wrong here.

<?php
$errors = array();
// ....create database connection.....//
if (isset($_POST['insert'])) {

$last_name = trim($_POST['last_name']);
$first_name = trim($_POST['first_name']);
$age = trim($_POST['age']);

// ....My regular expressions.....//
 if(isset($_POST['last_name'])){
 if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['last_name']) === 0) {
  $errors[] = 'lastname should not contain spaces.'; }
  }

if(isset($_POST['first_name'])){
if(preg_match("/^[A-Z][a-zA-Z -]+$/", $_POST['first_name']) === 0) {
  $errors[] = 'firstname should not contain spaces.';} 
}
  $OK = false;
   $stmt = $conn->stmt_init();
  $sql = 'INSERT INTO voter_tracking (
        v_id,
        last_name,
        first_name,)
    VALUES(?, ?,?)';
  if ($stmt->prepare($sql)) {
     $stmt->bind_param('iss', $_POST['v_id'], $_POST['last_name'],        $_POST['first_name']);
$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>
            <input type="text" name="last_name" class="widebox" id="name" required aria-required="true">
          </p>
          <p>
            <label for="first_name">First Name:</label>
            <input type="text" name="first_name" class="widebox" id="first_name" required aria-required="true">
          </p>

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

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

Your regex appears to be ok.

Your problem is that you need to check for errors before posting/inserting into database.. Something like this:

if (count($errors) > 0) {
   // prepare and execute sql insert here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM