Leilin Peng Share: PHP Form - Required field

  This section explains how we will set up a form required fields and error messages.

  PHP - Required fields

  In the previous section we have introduced validation rules table, we can see the "name", "E-mail", and "gender" field is required, each field can not be empty.

  Field validation rules

  Name Required. + Can only contain letters and spaces

  E-mail is necessary. + Must contain a valid email address (including "@" and ".")

  URL Optional. If present, it must contain a valid URL

  Remarks optional. Multi-line fields (text fields).

  Sex necessary. Necessary to choose one.

  If in the previous section, all input fields are optional.

  In the following code we added some new variables: $ nameErr, $ emailErr, $ genderErr, and $ websiteErr .. These errors will be displayed on the variables required fields. We have also added a if else statements for each $ _POST variable. These statements will check whether the $ _POST variable is empty (php use of empty () function). If empty, the corresponding error message is displayed. If not empty, the data passed to test_input () function:

  

  // define variables and the default is set to null

  $nameErr = $emailErr = $genderErr = $websiteErr = "";

  $name = $email = $gender = $comment = $website = "";

  if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (empty($_POST["name"])) {

  $ NameErr = "name is required.";

  } else {

  $name = test_input($_POST["name"]);

  }

  if (empty($_POST["email"])) {

  $ EmailErr = "E-mail is required.";

  } else {

  $email = test_input($_POST["email"]);

  }

  if (empty($_POST["website"])) {

  $website = "";

  } else {

  $website = test_input($_POST["website"]);

  }

  if (empty($_POST["comment"])) {

  $comment = "";

  } else {

  $comment = test_input($_POST["comment"]);

  }

  if (empty($_POST["gender"])) {

  $ GenderErr = "Gender is required.";

  } else {

  $gender = test_input($_POST["gender"]);

  }

  }

  ?>

  PHP - error message

  In the following example HTML form, we added some scripts for each field, each script displays an error message when the information input error. (If the user does not fill in the information on the form is submitted it will output an error message):

  

 

  first name:

  *

  

  Email:

  *

  

  URL:

  

  

  Remarks:

  

  gender:

  Female

  male

  *

  

  

  

 

  View all PHP tutorial article: https://www.codercto.com/courses/l/5.html (edit: Leilin Peng Source: network intrusion deleted)

Guess you like

Origin www.cnblogs.com/linpeng1/p/11022921.html
Recommended