Jump to content

Form Validation


Garcia

Recommended Posts

I am having problems how to loop through all my fields and set an error if they are blank.

This is what I have now.

[code]
foreach($_POST as $value)
{
if ($password and $username == "")
{
  $message = "Please fill in the Password field!";
      include ('login_form.php');
  exit();
    }
}
[/code]

I am not sure how to set that up properly. I did have an If for each field and it would repeat the form multiple times with each error. So I stuck them together and not sure how to do it, and with the loop. Any help would be nice.

Thanks!
Link to comment
Share on other sites

Here's an example of form field validation from a form I use:

[code]<?php
// validate input and if form is already submitted once
if (!isset($_POST['submit'])) {

  showForm();

} else { //form submitted

  $error = 0;


  if(empty($_POST['name'])) {
    $error = 1;
    $errstr[] = "Please enter a name";
  }

  if(!preg_match("/^(?:[\w\d]+\.?)+@(?:(?:[\w\d]\-?)+\.)+\w{2,4}$/", $_POST['email'])) {
    $error = 1;
    $errstr[] = "Please enter a valid email address";
  }

  if (empty($_POST['subject'])) {
    $error = 1;
    $errstr[] = "Please enter a subject";
  }

  if(empty($_POST['message']) || preg_match("/^enter your message here$/i", $_POST['message'])) {
    $error = 1;
    $errstr[] = "Please enter a message or question so we can assist you.";
  }

  if(empty($_POST['imagetext'])) {
    $error = 1;
    $errstr[] = "Please validate the image code";
  } else {
    include "securimage.php";
    $img = new securimage();
    $valid = $img->check($_POST['imagetext']);

    if(!$valid) {
      $error = 1;
      $errstr[] = "The code you entered was incorrect";
    }
  }

  if ($error == 1) {
    echo "<center>\n<font style=\"color: #FF0000\">\n";
    foreach($errstr as $err) {
      echo "<li> " . $err . "</li>\n";
    }
    echo "</font>\n</center>\n<br />\n\n";

    showForm();

  }
?>[/code]
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.