简体   繁体   English

如何在jquery中检查文本字段中的空格

[英]How to check textfield for whitespaces in jquery

I have a form. 我有一张表格。 I want to put validation so that It will check if user enters white spaces or not. 我想进行验证,以便检查用户是否输入空格。 If its white spaces then show error. 如果它的白色空格则显示错误。 How could I do this? 我怎么能这样做?

In case you want to detect if there is any white space all through the user's input string, 如果您想通过用户的输入字符串检测是否有任何空白区域,

var str = $("input").val();
if( str.indexOf(" ") !== -1 )
{
    alert("bad input");
}

Example: http://jsfiddle.net/pYquc/ 示例: http//jsfiddle.net/pYquc/

Use jQuery.trim(str) which remove the whitespace or tabs and you can validate. 使用jQuery.trim(str)删除空格或制表符,您可以验证。

http://api.jquery.com/jQuery.trim/ http://api.jquery.com/jQuery.trim/

function doValidations(){
   if(jQuery.trim( $(".className").val())==""){
     alert("error message");
     return false;    
   }else{
     return true;
   }
}

<input type="submit" onclick="return doValidations();">
Try this usong javascript:
var v = document.form.element.value;
var v1 = v.replace("","");
if( v1.length == 0){
 alert("error");
}

OR you can use following functions:

 // whitespace characters
      var whitespace = " \t\n\r";

      /****************************************************************/

      // Check whether string s is empty.
      function isEmpty(s)
      { return ((s == null) || (s.length == 0)) }

      /****************************************************************/

      function isWhitespace (s)
      {
           var i;

           // Is s empty?
           if (isEmpty(s)) return true;

           // Search through string's characters one by one
           // until we find a non-whitespace character.
           // When we do, return false; if we don't, return true.

           for (i = 0; i < s.length; i++)
           {
                // Check that current character isn't whitespace.
                var c = s.charAt(i);

                if (whitespace.indexOf(c) == -1) return false;
           }

           // All characters are whitespace.
           return true;
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM