2012-07-11 34 views
2

我有一個表單。我想要驗證,以便它會檢查用戶是否輸入空格。如果它的空白處顯示錯誤。我怎麼能這樣做?如何檢查jQuery中空格的textfield

+0

你有沒有嘗試什麼?表單驗證是一個常見問題,並且存在大量信息。嘗試實施時遇到特定問題嗎? – 2012-07-11 09:26:00

+0

是的,我想驗證用戶是否輸入空格,即如果他進入多個空格,那麼他仍然可以註冊我不想要 – 2619 2012-07-11 09:51:05

回答

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

<input type="submit" onclick="return doValidations();"> 
+0

我已經在做這個。但是,當用戶只輸入空格,然後它仍然可以註冊我不想 – 2619 2012-07-11 09:50:08

+0

檢查編輯後 – 2012-07-11 10:10:59

9

如果要檢測是否存在任何空白都通過用戶的輸入字符串,

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

例子:http://jsfiddle.net/pYquc/

+0

這一個根本不工作。 – 2619 2012-07-11 09:51:21

+0

我想要用戶輸入一些abc字符串。如果他輸入abc,那就沒問題了。但是如果他輸入了多個空格,那麼它應該顯示一個錯誤。 – 2619 2012-07-11 09:56:11

+0

http://jsfiddle.net/pYquc/如果他進入一個單一的空間,它顯示「壞的輸入」 – 2012-07-11 10:08:03

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