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.
Related
<?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.');
}
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.
I have seen this question asked elsewhere but am unsure of how to put some validation into my particular form which will exclude a particular email address. I would like the form to be rejected if an email address is entered, lets say anything#anything.com. Please see code below. There is more but i believe this is the relevant part...
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){
foreach(array_keys($_COOKIE) as $value){
unset($_REQUEST[$value]);
}
}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"#") != 1 ||
stristr($_REQUEST['email']," ") ||
stristr($_REQUEST['email'],"\\") ||
stristr($_REQUEST['email'],":") ){
$errors[] = "Email address is invalid";
}
else{
$exploded_email = explode("#",$_REQUEST['email']);
if (empty($exploded_email[0]) ||
strlen($exploded_email[0]) > 64 ||
empty($exploded_email[1])){
$errors[] = "Email address is invalid";
}
else{
if(substr_count($exploded_email[1],".") == 0){
$errors[] = "Email address is invalid";
}
else{
$exploded_domain = explode(".",$exploded_email[1]);
if(in_array("",$exploded_domain)){
$errors[] = "Email address is invalid";
}
else{
foreach($exploded_domain as $value){
if(strlen($value) > 63 ||
!preg_match('/^[a-z0-9-]+$/i',$value)){
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
If I understand your code, the goal of the main part is to validate the format of the email given by the user.
First of all, there is a built-in php function for this ( PHP >= 5.2 ) : filter_var(). You can replace all this block of code with :
$email = trim($_REQUEST['email']);
if (!filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Email address is invalid";
}
Then, if you want to check the email is not in a blacklist, just do something like this :
// Fill this array the way you want : hard-write it, fetch from database...
$blacklist = array("email1#gmail.com", "email2#gmail.com");
// Put in lower case for easiest comparison
$email = strtolower($email);
if (in_array($email, $blacklist)) {
$errors[] = "Email address is blacklisted";
}
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!
}
}
//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
}