使用html表单和php对空白文本区域或默认值进行验证


Using html forms and php for validation on blank textarea or if default value is present

嗨,我有一个表单,我试图验证底部的文本区。我想要它,所以如果默认值是存在的,或者如果框是空的,它错误。这是我要查看的表单的一部分:

<form id="form" method="post" action="email.php">    
<p><label style="width: 400px; float: left; height: 20px" for="comments">Your enquiry details?</label>
<textarea style="width: 400px; height: 84px" id="comments" rows="1" cols="1" 
          onfocus="if (this.value == this.defaultValue) { this.value = ''; }" 
          name="comments">
e.g. There are 5 of us looking to hire either caravan for 7 nights on the dates above. Are we able to have BBQ's?
</textarea> </p>
 All sections MUST be completed!<br />
<p class="submit">    
<button type="reset">Reset</button>    
<button name="send" type="submit">Submit</button> </p></fieldset> </form>

这是我的PHP页面的一部分:

$string_exp = ".";
 if(!eregi($string_exp,$comments)) {
    $error_message .= 'You did not leave a comment!.<br />';

如果文本区域为空白(因为我有正则表达式"。",所以他们可以使用键盘上的任何东西进行评论),这可以正确工作,但我也希望它出错,如果它仍然说默认值"例如,我们有5个人希望在上述日期租用7个晚上的房车。"我们可以烧烤吗?"

我该怎么做?

亲切的问候

if(!$comments || $comments == 'There are 5 of us looking to hire either caravan for 7 nights on the dates above. Are we able to have BBQ's?')

如果文本只能在非ie浏览器中使用,你也可以使用HTML5占位符属性(demo):

<textarea ... placeholder="here are 5 of us looking to hire either caravan for 7 nights on the dates above. Are we able to have BBQ's?"></textarea>

扩展您的检查,包括您当前的检查,以及字符串检查。

$default = "e.g. There are 5 of us looking to hire either caravan for 7 nights on the dates above. Are we able to have BBQ's?"
if (($comments == "") || ($comments == $default))) {
   $error_message .= 'You did not leave a comment!.<br />';

额外的好处是,使用$default变量填充您的模板,这样您就不必在两个地方编写它了。

首先,eregi函数自php 5.3起已弃用。Preg_match才是正确的选择!

第二,如果要测试是否输入了no值,为什么不与…nothing比较呢?PHP将把空字符串视为假值。

第三,假设你有这个值,为什么不比较它呢?

if (!$comments || $comments === 'my default value') {
    $error_message .= 'You did not leave a comment!.<br />';
}

看一下php关于布尔值的文档

我可能误解了。但如果你想在服务器端验证(email.php)你只需要:

$default_comment = "There are 5 of us looking to hire either caravan for 7 nights on the dates above. Are we able to have BBQ's?"
$comments = (string)$_POST['comments'];
if( empty($comments) || $comments == $default_comment )
    $error_message .= 'You did not leave a comment!.<br />';