Reputation: 1049
So I have a basic form, you can either enter your email, or phone number, followed by a required username. So What I want to do is an option to enter only a phone number or email. So this is what I'm doing
Here are my variables
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$phone = htmlspecialchars($_POST['phone'], ENT_QUOTES, 'UTF-8');
How I check for the fields
if(empty($email) || empty($phone)){
$errors['num_em'] = "Enter a valid email or phone number";
}
And the markup
<p class="alternative">OR</p>
<div id="DIV_7">
<input type="text" name="email" placeholder="Email" id="INPUT_8" autocomplete="off"/>
</div>
The issue with this is it makes me enter both email and phone, which is weird since I'm using the OR
operator. Any ideas?
Upvotes: 0
Views: 56
Reputation: 19528
The way it is right now, it will fail if one or another is empty.
What you want is the AND
operator &&
.
if(!filter_var($email, FILTER_VALIDATE_EMAIL) && empty($phone))
{
$errors['num_em'] = "Enter a valid email or phone number";
}
Why?
Because if email is empty and phone is empty we fail.
But if email is not empty and phone is the requirement does not met so we are safe as in having 1 filled and the other empty or not.
Upvotes: 2
Reputation: 6411
Try this:
if ($email == "" && $phone == "") {
$errors['num_em'] = "Enter either a valid email or phone number";
} else if ((strlen($email) > 0) && (strlen($phone) > 0)) {
$errors['num_em'] = "Enter either a valid email or phone number";
}
This way if both fields are empty, it gives an error. If both fields are filled, you still get an error. So only 1 of the field can be entered.
Upvotes: 0