Jump to content

Validation - How can I validate a form with PHP

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
John Ugwuozor

John Ugwuozor

    Newbie

  • Members
  • Pip
  • 3 posts
How can I validate a form with PHP

Edited by Roger, 05 August 2010 - 02:59 PM.


#2
Orjan

Orjan

    Writes binary right handed and hex left handed

  • Moderators
  • 3,299 posts
Mainly, you check each value in the form and returns error messages and shows the form again if the validation failed. How you do it is so different to each form of validation
but an example could be:


if ($_POST['submit'] != "") {

// this is where we do the validation.

  if ($_POST['myfield'] == "") {

     $errormessage = "you need to write something";

  } else if (strlen($_POST['myfield'] > 30) {

    $errormessage = "Please don't write more than 30 characters";

}

if ($errormessage != "" || $_POST['submit'] == "") {

// if there is an error, or, the form isn't submitted yet, print the form

   echo '<form method="POST" action="form.php">';

   echo '<input type="text" name="myfield" value="'.$_POST['myfield'].'" />';

   echo '<input type="submit" name="submit" value="Send in form" />';

   echo $errormessage;

} else {

// what to do if the validation passed

   echo "you wrote ". $_POST['myfield'];

}


__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall

#3
Guest_johnny.dacu_*

Guest_johnny.dacu_*
  • Guests
Orjan has given to you a greate example. With other words you grap a value (if form method is post then use $_POST['var_name'] else if is get then... $_GET. Above example check if the value if empty or it has more than 30 chars. But there are many other options like checking if is a number, or if it has a pattern etc.