KodeInfo | Learning resources for web and mobile development

PHP Form Required

September 14th, 2014 06:28:40 by Irfan Iqbal Comments(0) - Views(5992)

In this chapter let us discuss how to make required fields and display error messages when needed.let us first see what required fields are

Required Fields:

Required fields are the mandatory fiels denoted by "*".If an required fiels is left empty an error message will be displayed.

Here * denotes that name,email fields should not be empty else an error will be displayed for example name is required or email is required.

Now you might be thinking how to validate the field is empty or not .We can use empty() method for validation let us see an example how to embed empty method.

<?php
$nameErr = $emailErr =  "";
$name = $email =  "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
  }
 
}
?>

Now let us make a HTML file to display an error.

<html>
<head>
<title>Test Form</title>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<input type="submit" name="submit" value="Submit"> 
</form></body></html>

The above code will display an error when name and email fields are left empty.

thanks switch to another posts for more details.

Author

  • Irfan Iqbal
    Irfan Iqbal

    Irfan is a web developer and consultant from India. He is the co-founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, manages everything related to marketing and seo for kodeinfo , works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus