Here is the html and Php code i have used:
<?php
require_once('include_function.php');
require_once('validation_functions.php');
$errors = array();
$message ="";
if(isset($_POST['submit'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if (array_key_exists('submit', $_POST)){
}
$fields_required = array("username","password");
foreach($fields_required as $field){
$value = trim($_POST[$field]);
if(!has_presence($value)){
$errors[$field]= ucfirst($field). " Cant Be blank";
}
}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Single page Submission</title>
</head>
<body>
<?php echo $message;?>
<?php echo form_error($errors)?>
<form action="form_with_validation.php" method="post">
Username<input type="text" name="username" value=""/><br/>
Password<input type="password" value="" name="password" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
And these are functions I have used
function has_presence($value){
return isset($value) && $value !=="";
}
function form_error($errors=array()){
$output = "";
if(!empty($errors)){
$output .="<div class=\"error\">";
$output .="Please fix the following errors";
$output .="<ul>";
foreach($errors as $key => $field){
$output .= "<li>{$field}</li>";
}
$output .="</ul>";
$output .="</div>";
}
return $output;
}
Can someone please guide me to validate the form using if array key exists So that I get error message next to Or below the input field or any other method which does the needful