2015-06-30 26 views
0

需要jQuery驗證代碼以允許用戶以4炭分鐘,15字符的最大隻鍵入字符[a-zA-Z], ,以允許jQuery驗證,以防止按鍵輸入用戶名

例如一個空間:Sakshi耆那

<script> 
    $(document).ready(function() { 
    $('#reg_name').keyup(function() { 
     var $th = $(this); 
     $th.val($th.val().replace(/[^a-zA-Z]/g, function(str) { 
     return ''; 
     })); 
    }); 
    }); 
</script> 
+1

就這樣您知道您輸入的示例用戶名是11個字符。 –

回答

2

試着做這樣的事情,(在這一點就像你已經在做,但允許空格)首先刪除不需要的字符

一旦你只得到了字符,則允許再檢查長度,如果它的下日一個4或高於10然後驗證它是一個錯誤(你也可以在onvalidate事件上做到這一點)。

一旦你擅長這一點,然後用空格分隔輸入的值,並檢查新創建的數組的長度。

舉例JS Fiddle就在這裏。

$(document).ready(function() {  
    $('#reg_name').keyup(function() { 
     var $th = $(this); 

     // Remove invalid characters (include spaces in the value chars, we will remove later) 
     $th.val($th.val().replace(/[^a-zA-Z\ ]/g, function(str) 
     { return ''; })); 

     // Check for the the username length 
     if ($(this).val().length > 10 || $(this).val().length < 4) 
     { 
      $(this).removeClass('good').addClass('error'); 
     } 
     else 
     { 
      $(this).removeClass('error').addClass('good');    
     } 

     var s = $(this).val().split(' '); 

     // if there are more than 1 spaces (2 elements in the array 's') 
     if (s.length > 2) 
     { 
      $(this).removeClass('good').addClass('error'); 
     } 
    });  
});