如何在正则表达式的keyup上仅替换当前错误的字符?

我希望从我的输入文本中替换任何不是护照格式(A9999999)的字符。我写了以下内容(此处为 jsfiddle):


HTML


Doc Type <input id='docType' value = 'PASS'/> <br>

Doc ID <input id='docId'/>

JS:


$(document).ready(function () {

    var docTypeVal = $("#docType").val();

    $('#docId').keyup(function() {

        if(docTypeVal == "PASS") {

            var $th = $(this);

            $th.attr("maxlength","8");


            if($th.val().length <= 1) {

                $th.val().replace(/[^a-zA-Z]/g, function(str) { 

                    alert('You typed " ' + str + ' ".\n\nPlease use correct format.'); 

                    return ''; 

                })

            }

            else if($th.val().length <= 8 && $th.val().length > 1) {

                $th.val().replace(/^(?!.*^([a-zA-Z]){1}([0-9]){7}$)/, function(str) { 

                    alert('You typed " ' + str + ' ".\n\nPlease use correct format.'); 

                    return ''; 

                })

            }

        }

    });

});

但是,首先,这不会替换任何字符(错误/正确)。其次,它会在我输入第二个字符的那一刻发出警报。如果它是字母表,它应该接受第一个字符(否则替换),从第二个到第 8 个字符它应该只接受数字(否则替换)。


泛舟湖上清波郎朗
浏览 157回答 2
2回答

繁星点点滴滴

参考了Twisty 的JS,发现应该如下图所示:if(docTypeVal == "PASS") {&nbsp; $(this).attr("maxlength","8");&nbsp; var term = $(this).val();&nbsp; var re = /^[a-zA-Z]{1}\d{0,7}$/i;&nbsp; if (re.test(term)) {&nbsp; &nbsp; &nbsp; $(this).removeClass("invalid");&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; $(this).addClass("invalid");&nbsp; &nbsp; &nbsp; $(this).val(term.replace(term.charAt(term.length-1),&nbsp;&nbsp; &nbsp; &nbsp; function(str) {&nbsp;&nbsp; &nbsp; &nbsp; alert('You typed " ' + str + ' ".\n\nPlease use correct format.');&nbsp;&nbsp; &nbsp; &nbsp; return '';&nbsp;&nbsp; &nbsp; }));&nbsp; &nbsp; return false;&nbsp; &nbsp;}&nbsp;}

慕沐林林

您可以使用 1 个正则表达式进行测试。/^[a-z]?\d{0,7}$/i这种模式看起来A9最多A9999999。它将失败AA或99。示例:https : //jsfiddle.net/Twisty/awL0onjg/20/JavaScript$(function() {&nbsp; var docTypeVal = $("#docType").val();&nbsp; $('#docId').keyup(function(e) {&nbsp; &nbsp; var exc = [&nbsp; &nbsp; &nbsp; 11, // Tab&nbsp; &nbsp; &nbsp; 127, // Del&nbsp; &nbsp; ];&nbsp; &nbsp; if (exc.indexOf(e.which) > -1) {&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; var term = $(this).val();&nbsp; &nbsp; var re = /^[a-z]?\d{0,7}$/i;&nbsp; &nbsp; console.log("Testing:", term, re.test(term));&nbsp; &nbsp; if (re.test(term)) {&nbsp; &nbsp; &nbsp; $(this).removeClass("invalid");&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; $(this).addClass("invalid");&nbsp; &nbsp; }&nbsp; });});.keydown()如果您想防止用户在该模式之外输入,请考虑使用。查看更多。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript