I have one form field. In that field it's possible for user to enter EMAIL or MOBILE. From a PHP page i got value. After that i want to check whether this is email id or mobile number. suppose email
means i want to email success,suppose mobile
means i want to show mobile success ,i think we have to write regular expression,but i don't know how to write regular expression for this problem?
<form action="#" method="POST" id="forgotForm">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Email OR Mobile" id="email" name="email" value="" aria-required="true" required="" data-msg-required="Please enter your email">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
</form>
home.php
<?php
$email=$_POST['email'];//here value it will come like 9986128658 or admin@gmail.com
?>
You can check the input using preg_match
$email=$_POST['email'];
$emailPattern = '/^\w{2,}@\w{2,}\.\w{2,4}$/';
$mobilePattern ="/^[7-9][0-9]{9}$/";
if(preg_match($emailPattern, $email)){
echo "Email Success!";
} else if(preg_match($mobilePattern, $email)){
echo "Mobile Success!";
} else {
echo "Invalid entry";
}
Checks for the valid email
- Email should have atleast two words length say
aa@aa.aa
- TLD should have atleast 2 characters and maximum of 4 characters
- To include domains like co.in, use -
/^\w{2,}@[\w\.]{2,}\.\w{2,4}$/
Checks for the valid mobile
- Mobile should have 10 characters length and should start either with 7 or 8 or 9, to remove that restriction, change the
$mobilePattern
to /^[0-9]{10}$/
- If it is not valid email or mobile, it returns error message
You can check if the value is a valid email address. If it is then you have an email, otherwise you can assume that it is a phone number:
$email = null;
$phone = null;
// The "email" field has been submitted
if (isset($_POST["email"])) {
// If it is an email then set the email variable
if (filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL)) {
$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
}
// If it is a number then set the phone variable
else if (filter_input(INPUT_POST, "email", FILTER_VALIDATE_INT)) {
$phone = filter_input(INPUT_POST, "email", FILTER_SANITIZE_NUMBER_INT);
}
}
if ($email !== null) {
echo "Submitted email: {$email}";
}
if ($phone !== null) {
echo "Submitted phone number: {$phone}";
}