验证脚本丢失字符

时间:2014-06-01 14:16:49

标签: javascript jquery validation

下面的脚本应该一次验证用户输入的每个类型字符,但它会丢失字符,并且它总是符号后的字符(例如:如果我输入14121982对于日期字段,我在文本字段中获得14/_2/_9822,在内部获得14/_2/_982。此外,文本字段内容与内容变量之间的差异也是一个问题。

的jsfiddle

http://jsfiddle.net/klebermo/f8U4c/41/

var counter;
var tam;
var str;
var regex;

$('.valida').each(function(){

    $(this).on('focus', function(e){
        regex = $(this).attr('pattern');

        counter = 0;
        tam = size_of(regex);
        str = generate_string(regex, tam);

        $(this).val(str);
    });

    $(this).on('keypress', function(e){
        var tecla = e.which;
        var tecla2 = String.fromCharCode(tecla);
        var t = type_of(regex, counter);

        if(typeof tecla == t) {
            str = replaceAt(str, counter, tecla2);
            //counter++;
        } else {
            if(t != 'number' && t != 'string') {
                str = replaceAt(str, counter, t);
                counter++;
            }
        }

        counter++;

        result = $("<div>");
        result.append( "counter = "+counter+"<br>" );
        result.append( "tecla2 = "+tecla2+"<br>" );
        result.append( "typeof tecla2 = "+typeof tecla+"<br>" );
        result.append( "typeof t = "+t+"<br>" );
        result.append( "str = "+str+"<br>" );
        $("#result").empty().append(result);

        $(this).val(str);
    });

});

任何人都可以看到这里有什么问题?

1 个答案:

答案 0 :(得分:0)

经过更多的试用后,我终于得到了一个正常的代码:

<强>的jsfiddle

http://jsfiddle.net/klebermo/f8U4c/78/

<强>码

$('.valida').each(function(){

    $(this).on('focus', function(e){
        regex = $(this).attr('pattern');

        counter = 0;
        tam = size_of(regex);
        str = generate_string(regex, tam);

        $(this).val(str);
    });

    $(this).on('keypress', function(e){
        e.preventDefault();

        var tecla = e.which;

        if(tecla >= 48 && tecla <= 57)
            var tecla2 = tecla - 48;
        else
            var tecla2 = String.fromCharCode(tecla);

        result = $("<div>");
        result.append( "tecla = "+tecla+"<br>" );

        var t = type_of(regex, counter);

        if(counter < tam) {
            if(t != 'number' && t != 'string') {
                str = replaceAt(str, counter, t);
                counter++;
            }

            t = type_of(regex, counter);

            if(typeof tecla2 == t) {
                result.append( "tecla2 = "+tecla2+"<br>" );
                str = replaceAt(str, counter, tecla2);
                counter++;
            }
        }

        result.append( "counter = "+counter+"<br>" );
        $("#result").empty().append(result);

        $(this).val(str);
    });

});