0

我正在使用 MySQL 和 PHP 订阅新闻信函脚本。当用户输入电子邮件并单击按钮时,电子邮件被添加到数据库中。

问题是在不输入电子邮件的情况下单击按钮时,数据库正在更新一个空记录。如何停止提交空字段并强制用户输入电子邮件?

这是我的 HTML:

<form id="myForm" action="update.php" method="post">
    <input type="hidden" name="action" value="update" />
    <input type="text" name="email" id="email" value="Enter your email here" onfocus="if (this.value == 'Enter your email here') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your email here';}" onwebkitspeechchange="this.value = this.value.replace('Enter your email here','')"; style=" color:#999; font-size:1em;width:200px; font-style:italic; font-family:"Times  New Roman", Times, serif;"/>
    <input class="button" type="image" src="rss.png" />
 </form>
4

5 回答 5

2

在我看来,您需要在接受用户输入并将其插入数据库之前进行一些表单验证。做你正在做的事情是危险的。

为什么不使用众多插件之一:

http://www.queness.com/post/10104/powerful-javascript-form-validation-plugins

于 2012-07-12T20:00:50.407 回答
0

理想情况下,您将在客户端(javascript/JQuery) 和服务器端(php) 验证表单。

为清楚起见,我将删除输入框中的内联代码以获取此信息:

<input type="text" name="email" id="email" value="Enter your email here" />

注意- 您可以使用

placeholder='Enter your email here'

在您的输入框中获得提示。

使用 HTML5 进行客户端验证

使用电子邮件格式验证创建必填字段:

<input type="email" name="email" id="email" value="Enter your email here" required="required"/>

使用 javascript/JQuery 的客户端验证 - example.js

查询:

$('#email').bind('blur', function() {
    if (!validateEmail($(this).val()) {
        // Add errors to form or other logic such as disable submit
    }
});
function validateEmail($email) {
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    return emailReg.test($email);
}

}

服务器端验证 - update.php

// Require the email
if (empty($_POST['email'])) {
    $error_message = 'You must enter an email!';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $error_message = 'Invalid email format. Example: example@example.example';
} else { // If no errors, continue processing the form
    // process the form, enter email
}

单独的 HTML5 将阻止提交表单,但是只有更新的浏览器支持 HTML5。

希望这有帮助!

于 2014-09-08T15:07:23.643 回答
0

这是关于使用 jquery 验证插件的有用教程:http: //docs.jquery.com/Plugins/Validation

忽略他们示例中的样式并专注于核心方面。在您的情况下,最有用的行是:

<input id="cemail" name="email" size="25"  class="required email" />
于 2012-07-12T20:05:44.057 回答
0

粗略地说,你需要做类似..

var form = $('#mtForm');

$('input').change(function(){
   if($((this).val() == ''){
       form.unbind('submit').submit(function(){
           return false;
       });
   }
   else{
       form.unbind('submit');
   }
})
于 2012-07-12T20:05:54.157 回答
0
  1. 您应该将value电子邮件字段的属性更改为placeholder属性。和代码可以从电子邮件输入标签中删除onfocusonwebkitspeechchangeonblur
  2. 如果这是您所追求的唯一验证类型(下面是用 jQuery 编写的),您可以使用类似这样的东西来检查空白字段。

    $(function(){
        $('#myForm').submit(function(e){
            if ($('#email').val().trim() == "") {
              // some sort of notification here
              e.preventDefault();
              return false;
            }
        });
    });
    

    ​</p>

于 2012-07-12T20:05:57.973 回答