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;
}
Related
I am validating a sign in page form in PHP I have this code:
if($customerCount > 0) {
if(password_verify($password_2, $customer['password'])) {
if($customer['isEmailConfirmed'] == 0) {
$msg_2 = "<span class='text-danger'>Please verify your email!</span>";
} else {
$customer_id = $customer['id'];
login_2($customer_id);
}
} else {
$msg_2 = "<span class='text-danger'>The email address and password combination you provided was not found. Please try again.</span>";
}
} else {
$msg_2 = "<span class='text-danger'>The email address is not registered in our system.</span>";
}
And it works fine. But I need to add
if(empty($_POST['email_3']) || empty($_POST['password_3'])){
$msg_2 = 'You must provide email and password.';
}
If both email and password and left blank. Also I need to display message if email is filled but password blank and vice versa. Now how could I add these codes to my validation. I'm getting confused and lost about all these if statements. Where should I add these and how ??
<?php
// changed || to &&
if(empty($_POST['email_3']) && empty($_POST['password_3'])) {
$msg_2 = "<span class='text-danger'>You must provide email and password.</span>";
}
// No need to write this code.
else if(empty($_POST['email_3']) && !empty($_POST['password_3'])) {
$msg_2 = "<span class='text-danger'>Please enter a valid email address.</span>";
}
/*
You can write this code for validate email
else if(!empty($_POST['email_3']) && filter_var($_POST['email_3'], FILTER_VALIDATE_EMAIL) === false) {
$msg_2 = "<span class='text-danger'>Please enter a valid email address.</span>";
}
*/
else {
// Please write your remaining code
if($customerCount > 0) {
if(password_verify($password_2, $customer['password'])) {
if($customer['isEmailConfirmed'] == 0) {
$msg_2 = "<span class='text-danger'>Please verify your email!</span>";
} else {
$customer_id = $customer['id'];
login_2($customer_id);
}
} else {
$msg_2 = "<span class='text-danger'>The email address and password combination you provided was not found. Please try again.</span>";
}
} else {
$msg_2 = "<span class='text-danger'>The email address is not registered in our system.</span>";
}
}
?>
You can use a sequential algoritm. In this way it is easy to add a lot of validation, keeping the readability ok.
$everythingOk = true;
$errMessage = '';
if (empty($_POST['email_3']) {
$everythingOk = false;
$errMessage = 'Email 3 empty';
}
if ($everythingOk && empty($_POST['password_3']) {
$everythingOk = false;
$errMessage = 'Password 3 empty';
}
if ($everythingOk && ($customerCount === 0)) {
$everythingOk = false;
$errMessage = 'Customer count error';
}
........
if ($everythingOk) {
// all info ok, move on
} else {
// info is not valid
// message is in $errMessage
}
It might be easier to place it all into a function and return a result. The way you are doing your if statements you end up with a big V and makes it very hard to read at times:
<?php
$loginCheck = getLogin( $_POST , $customer , $password_2 );
if( is_array( $loginCheck ) ){ // if error messages are present
// Login errors
foreach( $loginCheck as $errorMsg ){
echo $errorMsg . '<br />';
}
}
if( $loginCheck ){ //assuming login_2 returns boolean true if logged in
echo 'Logged In!';
}
function getLogin( $details , $customer , $password ){
$errors[]; //set errors array to catch all errors
if(empty($details['email_3'])){
$errors[] = "You must provide an email.";
}
if(empty($details['password_3'])){
$errors[] = "You must provide a password.";
}
if( ! empty( $errors[] ) ){
//fatal error no point going futher
return $errors;
}
if( ! $customer ) { //assuming if no email is found $customer returns boolean
$errors[] = "<span class='text-danger'>The email address is not registered in our system.</span>";
}
if( ! password_verify( $password , $customer['password'] ) ) {
$errors[] = "<span class='text-danger'>The email address and password combination you provided was not found. Please try again.</span>"
}
if($customer['isEmailConfirmed'] === 0) {
$errors[] = "<span class='text-danger'>Please verify your email!</span>";
}
return login_2($customer['id']);
}
?>
Try this code:
<?php
if(empty($_POST['email_3'])) {
// Email is left blank
if(empty($_POST['password_3'])) {
// Password is also blank
$msg_2 = "You must provide email and password.";
} else {
// Only email is blank
$msg_2 = "You must provide email address.";
}
} elseif(empty($_POST['password_3']) && !empty($_POST['email_3'])) {
// Only password is blank
$msg_2 = "You must provide a password.";
}
}
// Your custom form validation goes here
?>
The first if checks whether the email is blank or not. The nested if checks meanwhile if the password is also blank. If this is the case, the message You must provide email and password. is assigned to $msg_2; otherwise this is You must provide email address..
The elseif checks if the password is empty AND if the email is not empty. If this is the case, the third message is put into $msg_2.
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.
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
//validate email
if(empty($email)){
$mailErr = "<div class='errors'>Email can not be empty.</div>";
}else{
if(!(preg_match("/^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/", $email))){
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
}
}
//validate message
if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
}
if both validation are true then send mail. please help me. How can I write this condition. I want if both conditions are fulfill then send the mail.
// Validate email
if (empty($email)) {
$mailErr = "<div class='errors'>Email can not be empty.</div>";
} else if (!(preg_match("/^[a-zA-Z0-9\-_]+(\.[a-zA-Z0-9\-_]+)*#[a-z0-9]+(\-[a-z0-9]+)*(\.[a-z0-9]+(\-[a-z0-9]+)*)*\.[a-z]{2,4}$/", $email))){
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
} else {
$valid_email = true;
}
// Validate message
if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
}else{
$valid_message = true;
}
if ($valid_email && $valid_message) {
// Send the email
}
There is a short form to validate Email-Adresses using FILTER_VALIDATE_EMAIL and you can just safe a variable, which contains an error status.
$error = false;
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
$error = true;
}
if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
$error = true;
}
if(!$error) {
//Send message here
}
You can also use a short form (but not checking both at the same time) without using a status variable:
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$mailErr = "<div class='errors'>Please input a valid email address.</div>";
} else if (empty($message)) {
$messageErr = "<div class='errors'>Message can not be empty.</div>";
} else {
//Send message here
}
I have a form that updates a users information upon submit. The current setup only allows the form to be submitted if all fields are filled out. I need to create if statements for each field that says if populated, update, if not, dont.
I have the password field listed below that describes what I want to do for each and every field, but I wasnt sure if I could list multiple variables inside the IF or do I have to write separate IF statements and select from the database every time
if($password != '') {
if($password != $password2) {
$error = '<div class="error_message">Attention! Your passwords did not match.</div>';
}
if(strlen($password) < 5) {
$error = '<div class="error_message">Attention! Your password must be at least 5 characters.</div>';
}
if($error == '') {
$sql = "UPDATE login_users
SET restricted = '$restrict',
company_name = '$company_name',
contact = '$contact',
email = '$email',
user_level = '$level',
password = MD5('$password')
WHERE user_id = '$id'";
$query = mysql_query($sql) or die("Fatal error: ".mysql_error());
echo "<h2>Updated</h2>";
echo "<div class='success_message'>User information (and password) updated for User ID <b>$id ($company_name)</b>.</div>";
echo "<h2>What to do now?</h2><br />";
echo "<a href='xxxxxxxx'>« Back to Admin Panel</a> | Go to the <a href='user_edit.php'>edit users</a> page.</li>";
}
Here is some more of my code
if(trim($id) == '1') {
$error = '<div class="error_message">Attention! You cannot edit the main Administrator, use database.</div>';
} else if(trim($company_name) == '') {
$error = '<div class="error_message">Attention! You must enter a company name.</div>';
} else if(trim($contact) == '') {
$error = '<div class="error_message">Attention! You must enter a contact name.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have entered an invalid e-mail address, try again.</div>';
} else if(trim($level) == '') {
$error = '<div class="error_message">Attention! No user level has been selected.</div>';
}
I need to create if statements for
each field that says if populated,
update, if not, dont.
You can build your SQL statement as you go. Something along the lines of:
$sqlCols = '';
$error = '';
// Password
if ($password != '') {
if ($password == $password2) {
if (strlen($password) > 4) {
$sqlCols .= "password = MD5('".mysql_real_escape_string($password)."'), ";
} else {
$error .= '<div class="error_message">Attention! Your password must be at least 5 characters.</div>';
}
} else {
$error .= '<div class="error_message">Attention! Your passwords did not match.</div>';
}
}
// Email
if ($email != '') {
if (isValidEmail($email)) {
$sqlCols .= "email ='".mysql_real_escape_string($password)."', ";
} else {
$error .= '<div class="error_message">Attention! Your email is invalid.</div>';
}
}
if ($error == '') {
$sql = "UPDATE login_users
SET ".trim($sqlCols, ', ')."
WHERE user_id = '$id'";
// etc...
}
In the near future, switch over to PDO for improved performance and better protection against SQL injection.
It depends on what kind of user feedback you want, but here's a simple approach that collects the fields that pass validation, and uses them for the query.
$errors = array();
$fields = array();
if( ($password != $password2) {
$errors[] = "Passwords didn't match";
$fields['password'] = $password;
}
if(empty($email)) {
$errors[] = "Email is empty";
$fields['email'] = $email;
}
if($something > $nothing) { //
$errors[] = "More errors";
$fields['something'] = $something;
}
//and so on...
if(!count($errors)) {
$str = '';
foreach($fields as $field => $val ) {
$str .= $field. "= '" .$val."', ";
}
$str = substr($str,0,1); //removes last , (comma)
$sql = "UPDATE login_users
SET $str
WHERE user_id = '$id'";
//do query..
}