? 最大长度为 60。 字符串中的整数不能超过10。 例如,如果用户粘贴到输入中: INV-1-6ren">
gpt4 book ai didi

javascript - 正则表达式 : how to limit max number of integers in an alphanumeric field

转载 作者:行者123 更新时间:2023-11-30 07:30:39 25 4
gpt4 key购买 nike

我的指示是用户可以在字段中输入所有字符,除了这些:

~`!@#$%^&*()_+={}[]|\;"',<>?

最大长度为 60。

字符串中的整数不能超过10。

例如,如果用户粘贴到输入中:

INV-123-RT-123456789-TR-123

那么正则表达式应该输出:

INV-123-RT-1234567-TR-

这是我的代码。我坚持从字符串末尾删除多余的整数。

 $('.isInvoiceNumber').on("input", function(e) {

var pos = this.selectionStart;

var str = $(this).val().replace(/[\~\`\!\@\#\$\%\^\&\*\(\)_\+\=\{\}\[\]\|\\\;\"\'\,\<\>\?]/g, '').replace(/\.{2,}/g, '.');

var digits = str.replace(/[^0-9]/g,"").length;
if ( digits>10 ) {
// ??
}

var len = str.length;
$(this).val(str);
this.selectionEnd = pos - ( len-str.length );
});

-->下面是 Codepen 以简化操作: https://codepen.io/btn-ninja/pen/vJrXbX

谢谢!

最佳答案

试试这个:

function limit( str ) {
var patt = /[~`!@#\$%\^&\*()_\+={}\[\]\|\;\"\'\,\<\>\?]/g;
var strWithoutSpecialChars = str.replace(patt,'') ;
var count = 0, result = '', numberDigit = 0 ;
for (var i = 0; i < strWithoutSpecialChars.length && count < 60; i++ ) {
var ch = strWithoutSpecialChars[i] ;
if ( /\d/.test(ch) ) {
numberDigit++;
if ( numberDigit < 15 ) { result += ch; count++ ; }
else { continue ; }
}
else { result += ch; count++ ; }
}
return result ;
}

var longText = 'Miusov, 5699999999as a man man of breeding and 555deilcacy, could 98955not but feel some inwrd qualms, when he reached the Father Superiors with Ivan: he felt ashamed of havin lost his temper. He felt that he ought to have disdaimed that despicable wretch, Fyodor Pavlovitch, too much to have been upset by him in Father Zossimas cell, and so to have forgotten himself. "Teh monks were not to blame, in any case," he reflceted, on the steps. "And if theyre decent people here (and the Father Superior, I understand, is a nobleman) why not be friendly and courteous withthem? I wont argue, Ill fall in with everything, Ill win them by politness, and show them that Ive nothing to do with that Aesop, thta buffoon, that Pierrot, and have merely been takken in over this affair, just as they have.';

var result = limit(longText) ;
console.log('Length : ' + result.length ) ;
console.log( 'String : ' + result ) ;

关于javascript - 正则表达式 : how to limit max number of integers in an alphanumeric field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com