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
https://forums.phpfreaks.com/topic/34099-form-validation/
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
https://forums.phpfreaks.com/topic/34099-form-validation/#findComment-160375
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.