我想从输入文本中替换任何非护照格式(A9999999)的字符。我写了以下(jsfiddle here):
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个字符,应仅接受数字(否则请替换)。