Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery验证以防止用户名按键_Jquery - Fatal编程技术网

jQuery验证以防止用户名按键

jQuery验证以防止用户名按键,jquery,Jquery,需要jQuery验证代码以允许用户仅键入char[a-zA-Z], 最少4个字符,最多15个字符,允许一个空格 例如:萨基·贾因 <script> $(document).ready(function() { $('#reg_name').keyup(function() { var $th = $(this); $th.val($th.val().replace(/[^a-zA-Z]/g, function(str) { retu

需要jQuery验证代码以允许用户仅键入char
[a-zA-Z]
, 最少4个字符,最多15个字符,允许一个空格

例如:萨基·贾因

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

$(文档).ready(函数(){
$('#reg_name').keyup(函数(){
var$th=$(本);
$th.val($th.val().replace(/[^a-zA-Z]/g,函数(str){
返回“”;
}));
});
});

尝试这样做,首先删除不需要的字符(就像您已经做的那样,但此时允许空格)

一旦您只获得了允许的字符,然后检查长度,如果长度小于4或大于10,则将其验证为错误(您也可以在
onvalidate
事件中执行此操作)

一旦你在这一点上做得很好,然后按空格分割输入值,并检查新创建数组的长度

这里有一个例子

$(文档).ready(函数(){
$('#reg_name').keyup(函数(){
var$th=$(本);
//删除无效字符(在值字符中包含空格,我们稍后将删除)
$th.val($th.val().replace(/[^a-zA-Z\]/g,函数(str)
{返回“”;}));
//检查用户名长度
如果($(this.val().length>10 | |$(this.val().length<4)
{
$(this.removeClass('good').addClass('error');
}
其他的
{
$(this.removeClass('error').addClass('good');
}
var s=$(this.val().split(“”);
//如果有超过1个空格(数组中的2个元素)
如果(s.长度>2)
{
$(this.removeClass('good').addClass('error');
}
});    
});

您只需知道您输入的示例用户名是11个字符。
$(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');
        }
    });    
});