試着做這樣的事情,(在這一點就像你已經在做,但允許空格)首先刪除不需要的字符
一旦你只得到了字符,則允許再檢查長度,如果它的下日一個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');
}
});
});
就這樣您知道您輸入的示例用戶名是11個字符。 –