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?
<?php
class validation {
public $firstName, $lastName, $errorFirstName = '', $errorLastName = '';
function __constructor($fName, $lName){
$this->firstName = $fName;
$this->lastName = $lName;
}
function check(){
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($this->firstName)){
$this->errorFirstName = 'First name is required';
} else {
$this->errorFirstName = 'Input is okay';
}
if(empty($this->lastName)){
$this->errorLastName = 'Last name is required';
} else {
$this->errorLastName = 'Input is okay';
}
}
}
}
$obj = new validation($_POST['firstname'], $_POST['lastname']);
$obj->check();
$errorF = $obj->errorFirstName;
$errorL = $obj->errorLastName;
?>
<!DOCTYPE html>
<html lang = "en-US" dir = "ltr">
<head>
<title>Home</title>
<meta charset = "UTF-8"/>
</head>
<body>
<form method = "POST" action="<?php echo $_SERVER["PHP_SELF"]?>">
<label>First Name: </label>
<input type = "text" name = "firstname" placeholder = "John"/>
<p class = "error"><?php echo $errorF;?></p>
<label>Last Name: </label>
<input type = "text" name = "lastname" placeholder = "Doe"/>
<p class = "error"><?php echo $errorL;?></p>
<input type="submit">
</form>
</body>
</html>
if($_SERVER["REQUEST_METHOD"] == "POST"){
check in your class and have it wrapped around where you instantiate the object. – Maximinamaximize