如何防止用户只在textarea中键入空格

时间:2016-03-25 17:05:46

标签: php html

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

例如,这是我的textarea:

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

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

消息可以以空格字符开头,但它不仅可以是空格字符。

5 个答案:

答案 0 :(得分:1)

要做到这一点你可以使用它,这不仅会检查空格,还会检查任何其他形式的空白区域:

{{1}}

答案 1 :(得分:0)

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

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

alert("error");
}

答案 2 :(得分:0)

正如提到的评论,您应该查看PHP和/或JavaScript的TRIM function

  

此函数返回一个字符串,其中从str的开头和结尾剥去了空格。如果没有第二个参数,trim()将删除这些字符:

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

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

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

答案 3 :(得分:0)

在检查字符串是否为空之前,你可以trim

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

$trimmed = trim($text); 

答案 4 :(得分:0)

这是你的答案

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

您还可以在发送和使用trim修复php之前使用javascript进行检查:

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