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

标签 javascript jquery

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

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

最大长度为 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/

相关文章:

javascript - 来自greatmonkey默认缩放的谷歌地图链接

javascript - 是否有一种快捷方法可以防止两个独立的 javascript/jquery 片段相互冲突或影响?

javascript - 使用位置 : absolute; in CSS 时滚动条 "jerks"

jquery - 将选择中的值复制到文本

jQuery 多个固定粘性框

javascript - .replaceWith() 在 jQuery 1.9+ 中不起作用

javascript - Bootstrap 标签 : how to retrieve items from the input list to server side?

javascript - 从 jQuery 中的 select 元素生成逗号分隔的字符串

javascript - 箭头语法和函数语法真的相同吗? (无法读取未定义的属性 'createDocumentFragment')

javascript - 如果出现错误,则阻止表单提交