title: How to validate form field in PHP using Object Oriented Technique
body: <p>I have created a class 'validate' to validate two fields i.e 'firstname' and 'lastname'. It is not working fine, it is showing error when field is empty but when I submit the form with non-empty fields the error is still there. How to execute this on form submission?</p>
  
  <pre><code> &lt;?php
  
    class validation {
  
    public $firstName, $lastName, $errorFirstName = '', $errorLastName = '';
  
    function __constructor($fName, $lName){
      $this-&gt;firstName = $fName;
      $this-&gt;lastName = $lName;
    }
  
    function check(){
  
        if($_SERVER["REQUEST_METHOD"] == "POST"){
          if(empty($this-&gt;firstName)){
          $this-&gt;errorFirstName = 'First name is required';
         } else {
          $this-&gt;errorFirstName = 'Input is okay';
         }
  
       if(empty($this-&gt;lastName)){
           $this-&gt;errorLastName = 'Last name is required';
        }  else {
         $this-&gt;errorLastName = 'Input is okay';
        }
      }
     }
    }
  
   $obj = new validation($_POST['firstname'], $_POST['lastname']);
   $obj-&gt;check();
   $errorF = $obj-&gt;errorFirstName;
   $errorL = $obj-&gt;errorLastName;
  
   ?&gt;
  
    &lt;!DOCTYPE html&gt;
    &lt;html lang = "en-US" dir = "ltr"&gt;
     &lt;head&gt;
      &lt;title&gt;Home&lt;/title&gt;
      &lt;meta charset = "UTF-8"/&gt;
     &lt;/head&gt;
     &lt;body&gt;
     &lt;form method = "POST" action="&lt;?php echo $_SERVER["PHP_SELF"]?&gt;"&gt;
      &lt;label&gt;First Name: &lt;/label&gt;
      &lt;input type = "text" name = "firstname" placeholder = "John"/&gt;
      &lt;p class = "error"&gt;&lt;?php echo $errorF;?&gt;&lt;/p&gt;
      &lt;label&gt;Last Name: &lt;/label&gt;
      &lt;input type = "text" name = "lastname" placeholder = "Doe"/&gt;
      &lt;p class = "error"&gt;&lt;?php echo $errorL;?&gt;&lt;/p&gt;
      &lt;input type="submit"&gt;
     &lt;/form&gt;
    &lt;/body&gt;
   &lt;/html&gt;
  </code></pre>