【问题标题】:Validate email or mobile with regular expression使用正则表达式验证电子邮件或手机
【发布时间】:2016-05-31 04:36:29
【问题描述】:

我有一个表单域。在该字段中,用户可以输入 EMAILMOBILE。从 PHP 页面我得到了价值。之后,我想检查这是电子邮件 ID 还是手机号码。假设email 表示我想通过电子邮件发送成功,假设mobile 表示我想显示移动成功,我想我们必须编写正则表达式,但我不知道如何为这个问题编写正则表达式?

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

【问题讨论】:

    标签: php php-5.2


    【解决方案1】:

    您可以使用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. 检查有效的电子邮件

      • 电子邮件应至少有两个字长,如aa@aa.aa
      • TLD 应至少包含 2 个字符,最多包含 4 个字符
      • 要包含像 co.in 这样的域,请使用 - /^\w{2,}@[\w\.]{2,}\.\w{2,4}$/
    2. 检查有效的手机

      • Mobile 应该有 10 个字符的长度,并且应该以 7 或 8 或 9 开头,要取消该限制,请将 $mobilePattern 更改为 /^[0-9]{10}$/
    3. 如果它不是有效的电子邮件或手机,则返回错误消息

    【讨论】:

      【解决方案2】:

      您可以检查该值是否为有效的电子邮件地址。如果是,那么您有一个电子邮件,否则您可以假设它是一个电话号码:

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

      【讨论】:

        猜你喜欢
        • 2020-11-04
        • 1970-01-01
        • 2014-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多