Validate email or mobile with regular expression

≯℡__Kan透↙ 提交于 2020-04-07 06:33:05

问题


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
  
  ?>

回答1:


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";
}
  1. 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}$/
  2. 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}$/
  3. If it is not valid email or mobile, it returns error message



回答2:


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}";
}


来源:https://stackoverflow.com/questions/37536911/validate-email-or-mobile-with-regular-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!