Display Errors on validation - php

I use am using bootstrap.. I need to display errors 1 at a time. the following code post the errors in different rows and it consumes a whole page.
if there is an issue in the first field only post that error before continuing to the next field instead of posting all fields at once.
function validate_registration(){
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$email = clean($_POST['email']);
$user_name = clean($_POST['user_name']);
$birthdate = clean($_POST['birthdate']);
$country = clean($_POST['country']);
$password = clean($_POST['password']);
$confirm_password = clean($_POST['confirm_password']);
if (empty($email)) {
$errors[] = "Email Address Required.";
}
if (email_exists($email)) {
$errors[] = "Email Address in use.";
}
if (empty($user_name)) {
$errors[] = "Username Required.";
}
if (strlen($user_name) < $min) {
$errors[] = "Username is to short.";
}
if (user_exists($user_name)) {
$errors[] = "Username Taken.";
}
if (empty($birthdate)) {
$errors[] = "Birthdate Required.";
}
if (empty($country)) {
$errors[] = "Country Required.";
}
if (empty($password)) {
$errors[] = "Password Required.";
}
if ($password !== $confirm_password) {
$errors[] = "Your password fields do not match";
}
if (! empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
if (register_user($email, $user_name, $birthdate, $country, $password)) {
set_message('<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Please check your email for account Information.</div>');
redirect("../account/login.php");
}
}
}
}

You can also do the same by keeping your existing code.
Just replace this code:-
if (!empty($errors)) {
echo validation_errors($errors[0]);
}
You can also get the same functionality by if else if way. declare $error as a string.
$error = '';
if(empty($email)) {
$error = "Email Address Required.";
}
else if (email_exists($email)) {
$error = "Email Address in use.";
}
else if (empty($user_name)) {
$error = "Username Required.";
}
else if (strlen($user_name) < $min) {
$error = "Username is to short.";
}
else if (user_exists($user_name)) {
$error = "Username Taken.";
}
else if (empty($birthdate)) {
$error = "Birthdate Required.";
}
else if (empty($country)) {
$error = "Country Required.";
}
else if (empty($password)) {
$error = "Password Required.";
}
else if ($password !== $confirm_password) {
$error = "Your password fields do not match";
}
if (!empty($error)) {
echo validation_errors($error);
} else {
if (register_user($email, $user_name, $birthdate, $country, $password)) {
set_message('<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Please check your email for account Information.</div>');
redirect("../account/login.php");
}
}
For Bootstrap Validations, Just visit this link:-
Hope it will help you :)

UPDATED:
As per your comments, if you want to print one error at a time than you need to use ELSEIF instead of IF like:
if (empty($email)) {
$errors[] = "Email Address Required.";
}
elseif (email_exists($email)) {
$errors[] = "Email Address in use.";
}
...

Why are not using jquery validation for client side validation
and then use server side validation too but display it as all
error in loop instead of inline .
Because client as well as server side validation is useful

Related

validation of email FILTER_VALIDATE_EMAIL is not working but my error is not nbot solved function is not working

<?php
function validateUser($user)
{
$errors = array();
if (empty($user['username'])) {
array_push($errors, 'Username is required');
}
if (empty($user['email']) && !filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
array_push($errors, 'Email is required');
}
// if (!filter_var(($user, FILTER_VALIDATE_EMAIL) {
// array_push($errors, 'Email is required');
// }
if (empty($user['password'])) {
array_push($errors, 'Password is required');
}
// if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// $emailErr = "Invalid email format";
// }
if ($user['passwordconf'] !== $user['password']) {
array_push($errors, 'password do not match');
}
$existingUser = selectOne('users', ['email' => $user['email']]);
if ($existingUser) {
if (isset($user['update-user']) && $existingUser['id'] != $user['id']) {
array_push($errors, 'Email alraedy exists');
}
if (isset($user['create-admin'])) {
array_push($errors, 'Email alraedy exists');
}
}
return $errors;
}
change this
if (empty($user['email']) && !filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
array_push($errors, 'Email is required');
}
on this
if (empty($user['email']) || (!empty($user['email']) && !filter_var($user['email'], FILTER_VALIDATE_EMAIL))) {
array_push($errors, 'Email is required');
}
If you want to check for either an empty email or an invalid one in one if:
<?php
if (empty($user['email']) || !filter_var($user['email'], FILTER_VALIDATE_EMAIL)) {
array_push($errors, 'Email is required or invalid.');
}

Combine multiple php bootstrap alert box into one

i have a form which show error inside bootstrap alert, if username exist and if email exist. like in picture
now my question in how do i show alert in one single alert box
code
if (strlen($_POST['username']) < 3) {
$error[] = 'Username is too short.';
} else {
$stmt = $conn->prepare('Database query');
if (!empty($row['username'])) {
$error[] = 'Username provided is already in use.';
}
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error[] = 'Please enter a valid email address';
} else {
$stmt = $conn->prepare('Database query');
if (!empty($row['email'])) {
$error[] = 'Email provided is already in use.';
}
}
/ alert box
if (isset($error)) {
foreach ($error as $errors) {
echo "<div class='alert alert-danger small text-center' role='alert'>" . $error . "</div>";
}
}
if (isset($_GET['action']) && $_GET['action'] == 'joined') {
echo "<div class='alert alert-success small text-center' role='alert'>Registration successful.<br> Please check your email to activate your account.</div>";
}
i tried adding $error[] .= but still din't work, any solution.
this is how i want my alert box to be
try this
<?php
if (strlen($_POST['username']) < 3) {
$error[] = 'Username is too short.';
} else {
$stmt = $conn->prepare('Database query');
if (!empty($row['username'])) {
$error[] = 'Username provided is already in use.';
}
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error[] = 'Please enter a valid email address';
} else {
$stmt = $conn->prepare('Database query');
if (!empty($row['email'])) {
$error[] = 'Email provided is already in use.';
}
}
// alert box
if (isset($error)) {
$errorMsg = "<div class='alert alert-danger small text-center' role='alert'><ul>";
foreach ($error as $errors) {
$errorMsg .= '<li>' . $error . '</li>';
}
$errorMsg .= '</ul></div>';
echo $errorMsg;
}

php validate email extension type

This is my code to validate email, it works great but I want if the email does not end with a .mil it says invalid email
if (isset($_POST['update_email'])) {
$email = escape($_POST['email']);
if (empty($email)) {
$errors[] = "Email Address Required.";
}
if (email_exists($email)) {
$errors[] = "Email Address in use.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = "Invalid Email Address";
}
if (! empty($errors)) {
echo validation_errors($errors[0]);
} else {
}
Thanks.
Add a regular expression conditional statement
if (!preg_match('/\.mil$/', $email) {
$errors[] = "Invalid Email Address";`
}
Or perhaps you can build this logic inside email_exists.

Form validation in php is not working properly

Can anyone tell me what wrong i am doing here ? Error shows only if the First name is blank, for the rest (e.g lastname/email/body) it's not working. EMail validation also not working.
$error = "";
if (empty($fanme)) {
$error = "First name must not be empty !";
}
elseif (empty($lname)) {
$error = "Last name must not be empty !";
}
elseif (empty($email)) {
$error = "email must not be empty !";
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Invalid Email Address !";
}
elseif (empty($body)) {
$error = "Message field not be empty !";
}
else {
$msg = "ok";
}
}
if (isset($error)) {
echo "<span style='color:red'>$error</span>";
}
if (isset($msg)) {
echo "<span style='color:green'>$msg</span>";
}
It looks like you misspelled "$fname" in line 2 of your code above.

How to put my validation block of codes into Function PHP

How can I put my validation codes into a function? How am I going to return it and call it? I am trying to call put them in just one code and then call them in a function for my forms. Any idea?
Here's my codes:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
$errors[] = "email cannot be blank";
}
if(empty($_POST['first_name']))
{
$errors[] = "First Name cannot be blank";
}
if(empty($_POST['last_name']))
{
$errors[] = "Last Name cannot be blank";
}
if(empty($_POST['password']))
{
$errors[] = "Password cannot be blank";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
$errors[] = "Please enter matching password";
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
$errors[] = "Birth Date cannot be blank";
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = $errors;
//redirect your user back using header('location: ')
header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
//redirect your user to the next part of the site!
}
}
So when I call this this wont work:
echo validate();
Hope you can help. Thanks!
So you're saying something like:
class Validation {
public static function emailFilter($input) {
global $_POST;
return empty($_POST['email']) AND filter_var($input,
FILTER_VALIDATE_EMAIL) != false ? "email cannot be blank" : false;
}
}
Or are you looking to do something else?
EDIT 1
Okay, how about:
function filter ($input, $type) {
if (!$input OR !$type) {
switch ($type) {
case "email":
// Check email
if (empty($_POST['email']) AND filter_var($input, FILTER_VALIDATE_EMAIL)) {
return "email cannot be blank";
}
break;
case "first_name":
if(empty($_POST['first_name']))
{
return "First Name cannot be blank";
}
break;
// And so on.
}
}
}
You could call it then by:
filter($_POST['email'], 'email');
So then:
if (!filter($_POST['email'], 'email')) {
// The email checks out.
} else {
$error[] = filter($_POST['email'], 'email');
}
There are will be more elegant solutions available, but this is based on what I think you want.
Let's say that the user clicks the button after filling-up the required fields, in your $_POST['submit'] or whatever name of your button, just add your codes, and print the error beside the html textbox by adding or if you want, just print $error below the textboxes of your html registration page. And if the errors return zero value, then you can add everything in the database then redirect to your desired page in the else block of your error checking codes.
I would do this like so:
function validate(){
$errors = array();
//empty array to collect errors
//VALIDATION CODES (NEED TO BE INSIDE A FUNCTION)
if(empty($_POST['email']) AND filter_var($email, FILTER_VALIDATE_EMAIL) != false)
{
array_push($errors, "Email cannot be blank");
}
if(empty($_POST['first_name']))
{
array_push($errors, "First Name cannot be blank");
}
if(empty($_POST['last_name']))
{
array_push($errors, "Last Name cannot be blank");
}
if(empty($_POST['password']))
{
array_push($errors, "Password cannot be blank");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(empty($_POST['confirm_password']) AND $_POST['password'] == $_POST['confirm_password'])
{
array_push($errors, "Please enter matching password");
}
if(!isset($_POST['date']) || strtotime($_POST['date']) === false)
{
array_push($errors, "Birth Date cannot be blank");
}
if(!empty($errors))
{
//if there are errors, assign the session variable!
$_SESSION['errors'] = implode("|", $errors);
//redirect your user back using header('location: ')
return 0;
/*
Can't use both return & redirect, but return is more flexible.
*/
//header('Location: registration_page.php');
}
else
{
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$password = $_POST['password'];
$birth_date = $_POST['date'];
return array("email" => $email, "first_name" => $first_name,
"last_name" => $last_name, "password" => $password,
"birth_date" => $birth_date);
// so now you have your results in an associative array.
// you can use print_r(validate()); to see the results, or use
// $r = validate(); if ($r != false) { /*go places!*/}
//redirect your user to the next part of the site!
}
}

Categories