【问题标题】:How to prevent a user from just typing spaces in a textarea如何防止用户只在文本区域中输入空格
【发布时间】:2016-07-13 11:28:57
【问题描述】:

我见过许多其他问题,主要是询问如何防止在整个文本区域中输入空格,但我想知道如何检查文本区域是否只包含空格?

例如,这是我的文本区域:

<textarea id='textarea' name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea>

我可以通过以下方式轻松检查以上内容是否为空:

$post_msg = htmlentities(strip_tags(@$_POST['msg']));
$post_msg=mysqli_real_escape_string($connect,$post_msg);
if ($post_msg != "") {
  // do this
}

但是,如果用户只输入空格字符,那么该字段显然不再为空,上述检查无效。如何检查用户是否输入了空格字符?

消息可以以空格字符开头,但不能只是空格字符。

【问题讨论】:

  • empty 是比检查它是否不是空字符串更好的选择。 php.net/empty
  • trim、ltrim、rtrim 都是可以用来删除空格的函数。 trim 将删除字符串开头和结尾的空格,ltrim 从左侧删除,rtrim 从右侧删除。
  • 修剪值,然后检查它是否为空。

标签: php html


【解决方案1】:

为此,您可以使用它,这不仅会检查空格,还会检查任何其他形式的空格:

$post_msg = htmlentities(strip_tags(@$_POST['msg']));
$post_msg=mysqli_real_escape_string($connect,$post_msg);
$post_msg_check=preg_replace('/\s+/', '', $post_msg);
if ($post_msg_check == "") {
  // User's entry is blank $post_msg is the user's entry
} else {
  // User's entry is not blank $post_msg is the user's entry
}

【讨论】:

  • 这将删除所有空格,而不仅仅是多余的空格。
  • preg_replace 仅用于检查字符串,我将编辑我的答案以使其更清楚,而 htmlentities 是他在以前的代码中不好的东西,所以它必须存在是有原因的。跨度>
【解决方案2】:

正如 cmets 所提到的,您应该查看TRIM function 的 PHP 和/或 JavaScript。

这个函数返回一个字符串,从 str 的开头和结尾去掉空格。如果没有第二个参数,trim() 会去掉这些字符:

  • " " (ASCII 32 (0x20)),一个普通的空格。
  • “\t”(ASCII 9 (0x09)),一个制表符。
  • “\n”(ASCII 10 (0x0A)),换行(换行)。
  • "\r" (ASCII 13> (0x0D)),回车。
  • “\0”(ASCII 0 (0x00)),NUL 字节。
  • “\x0B”(ASCII 11 (0x0B)),垂直制表符。

为了实现,我很早就喜欢 Trim,所以我可能会使用 htmlentities() 行来实现

$post_msg = htmlentities(trim(strip_tags(@$_POST['msg'])));

【讨论】:

    【解决方案3】:

    使用javascript函数trim()它会删除空格并检查用户是否输入了空字符串

    var str =  document.getElementById("id").value;
    if(str.trim() == '') {
    
    alert("error");
    }
    

    【讨论】:

    • 不要依赖客户端。在服务器上执行。
    • @CharlotteDunois 我认为应该在客户端和服务器上完成。服务器为您自己的理智和保护。用户体验的客户。
    【解决方案4】:

    你可以trim你的字符串,然后再检查它是否为空

    http://php.net/manual/en/function.trim.php

    $trimmed = trim($text); 
    

    【讨论】:

      【解决方案5】:

      这是你的答案

      $post_msg = htmlentities(strip_tags(@$_POST['msg']));
      $post_msg=mysqli_real_escape_string($connect,$post_msg);
      $post_msg_check_space=preg_replace('/\s+/', '', $post_msg);
      if ($post_msg_check_space==""){
         //there's only space
      }else{
         //there's things other than space, use $post_msg
      }
      

      您也可以在发送和检查 php 之前使用 javascript 检查:

      var string =  document.getElementById("id").value;
      var string_check_space = string.trim();
      if (string_check_space !=''){
         getElementById("buttonSubmit")[0].submit();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-20
        • 2020-07-02
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多