Мои инструкции заключаются в том, что пользователь может вводить в поле все символы, кроме следующих:
~`!@#$%^&*()_+ = {}[]|\;"',<>?
Максимальная длина 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 );
});
--> Вот Кодепен, чтобы было проще: https://codepen.io/btn-ninja/pen/vJrXbX
Спасибо!
«все символы, кроме этих…» — это гораздо больше, чем просто буквенно-цифровые символы. И что подразумевается под «Целые числа не должны быть больше 15»? Должно ли оно содержать не более 15 цифр? (но ваш код содержит digits>10
)
Спасибо TiiJ7, я отредактировал вопрос для ясности.
Просто проверьте это в своем условии if:
var str = str.substr(0, str.length-1);
Он удаляет последний введенный символ из входной строки.
Так:
$('.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 ) {
str = str.substring(0, 10);
}
var len = str.length;
$(this).val(str);
this.selectionEnd = pos - ( len-str.length );
});
Вы имеете в виду проверку ввода? Что-то вроде этого?:
//use 'keydown' to prevent copy pasting invalid values
var inputLength = 0;
$('#invoice').on('keydown', function(){inputLength = $(this).val().length});
//check against criteria set upon input
$('#invoice').on('keyup', function(){
if ($(this).val().length>60 || $(this).val().match(/[0-9]/g).length>15 || $(this).val().match(/[^\w^0-9]/)){
$(this).val($(this).val().slice(0,inputLength-$(this).val().length));
}
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id = "invoice"></input>
Попробуй это:
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.info('Length : ' + result.length ) ;
console.info( 'String : ' + result ) ;
Вы можете использовать числовое поле HTML5 с атрибутом max.