使值为所有空格的文本框无效

Make Textbox with Value of All Spaces Invalid

本文关键字:文本 无效 空格      更新时间:2023-12-16

我有这些脚本。。。

 Name: <input type="text" id="inputName" onblur="verifyName(this.value)">
 <script type="text/javascript">
    function verifyName(nameInput)
    {
       if(nameInput=="")
       {
          // error
          alert('please enter your name');
       }
       else
       {
          // accepted
       }
    }
 </script>

如果用户不想在文本框中输入自己的姓名,这将显示一个错误。

如果用户懒惰,他/她会输入"(一个空格或更多)作为名称,该怎么办?这可以被JavaScript接受。在if条件下,它将返回false。

但我希望用户不要只输入空格。有办法做到这一点吗?

注:任何数量的空格(没有任何字母)都是无效的。


如果用户输入以下文本之一,JavaScript应接受/拒绝如下输入。。。

"John" --> valid
"" --> invalid
"John Doe" --> valid
"    " --> invalid
"John     Doe" --> valid (can be edited to remove too many spaces)
"      Kim" --> valid (can be edited to remove too many spaces)
" " --> invalid
function verifyName(nameInput)
{
   nameInput = nameInput.trim();
   if(nameInput=="")
   {
      // error
      alert('please enter your name');
   }
   else
   {
      // accepted
   }
}

trim()函数将删除所有空格。如果var中只有空格,则trim()返回"。

在进行检查之前修剪字符串。见下文

if(nameInput.trim()=="")
{
     // error
     alert('please enter your name');
}
else
{
 // accepted
}

函数的一个(相当多的)可能实现使用正则表达式:

function verifyName(nameInput) {
    return input.match(/'w{1,12}/) === null ? false : true;
    //                       ^^
    //    Or some other sensible limitation to the length of a name. 
}

您可以使用正则表达式替换字符串中的所有空格,然后检查其长度。如果删除所有空格后至少还有一个字符,那就是你的有效情况,对吧?

testInput = function(){
  var inpStr = $('#txtInp').val();
  
  
var teststr = inpStr.replace(/'s/g, "");
 
  //$('#testStrDiv').text(teststr);
  
  if((teststr.length)&&(teststr.length>0))
    {
      $('#divOutp').html('<b>Valid! </b>');
      }
  else{
        $('#divOutp').html('<b>Invalid! </b>');
      }
  
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txtInp" />
<input type="button" onclick="testInput()" value="test" />
<div id="testStrDiv" />
<div id="divOutp" />