【问题标题】:Validation of Email in PHP 5.2?在 PHP 5.2 中验证电子邮件?
【发布时间】:2012-04-10 17:09:20
【问题描述】:

您好,我在 PHP5.2 中验证电子邮件时遇到错误 看我下面的代码:我在脚本中调用了 checkemail() 并编写了函数 checkemail()。但我收到类似 Error: Duplicate entry '' for key 'PRIMARY' 之类的错误,因为我已将电子邮件 ID 声明为主键。当我在电子邮件 ID 中放入任何内容时,它会在数据库中接受。我认为功能没有正常执行。指导是否有合适的解决方案。如果需要任何详细信息,请告诉我。

<head>
<script>
  function checkEmail()
  {
    $strEmail= mysql_real_escape_string($_POST['email']);
    if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $strEmail))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
</script>
</head>
<body>
  <div class="container">
    <section id="content">
      <form name="form1" method="post" action="check_register.php">
        <div>
          <input type="text" placeholder="Enter username" required="" id="uname" name="uname"/>
        </div>
        <div>
          <input type="text" placeholder="Enter Email-id" required="" id="email" name="email" onfocus="checkEmail('email');"  />
        </div>
        <div>
          <input type="password" placeholder="Enter Password" required="" id="pass" name="pass"/>
        </div>
        <div>
          <input type="password" placeholder="Repeat Password" required="" id="rpass" name="rpass" onfocus="checkPassword(document.getElementById('pass'), this);" oninput="checkPassword(document.getElementById('pass'), this);"/>
        </div>
        <div>
          <input type="text" placeholder="Enter country" required="" id="country" name="country"/>
        </div>
        <div>
          <input type="submit" value="Register"  />
        </div>
      </form>
    </section>
  </div>
  <script src="form-validation.js"/></script>
</body>

【问题讨论】:

  • my+email@xxxxx.travel这样的地址呢?

标签: php mysql php-5.2


【解决方案1】:

是的,为什么不使用 filter_var

filter_var ($isEmail, FILTER_VALIDATE_EMAIL);

并且 eregi (Posix Regex) 已被弃用为 PHP 5.3.0。 php-manual

【讨论】:

    【解决方案2】:

    在尝试插入邮件之前,是否检查邮件是否已存在于数据库中?我想你的问题就在这里。无论 html5 还是电子邮件验证。

    顺便说一句,请不要使用&lt;script&gt; balise 来执行php 代码。请改用&lt;?php /* your code here */ ?&gt;

    您还可以使用内置的 PHP 函数使用 filter_var 验证您的电子邮件,查看第一个示例:http://www.php.net/manual/en/filter.examples.validation.php

    【讨论】:

    • j0k 是正确的:您收到的错误消息是由于您当前持有的数据 - 与验证无关 - 顺便说一句,正则表达式非常糟糕。考虑:/^[a-z0-9\._%+!$&*=^|~#%'`?{}/\-]+@([a-z0-9\-]+\.) {1,}([az]{2,6})$/gi(这也不是一个完整的解决方案)
    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 2017-03-19
    • 1970-01-01
    • 2012-10-04
    • 2017-10-12
    • 1970-01-01
    • 2011-08-16
    • 2011-03-30
    相关资源
    最近更新 更多