Javascript 仅验证文本框中预定义文本后的数字

Javascript to validate only Numeric after predefined text in a textbox

我正在尝试使用 Javascript 创建一个文本框,在文本框的开头包含一些只读文本,然后允许在只读文本之后进行编辑。我只需要在只读文本后允许 10 位数字,并且需要验证数字。以下是 Javascript 代码,用于在文本框

中设置只读
var readOnlyLength = $('#field').val().length;
 $('#output').text(readOnlyLength);enter code here
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
    && ((this.selectionStart < readOnlyLength)
    || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
}
});       

如果您正在寻找脚本解决方案,那么这里是纯 js 和 RegExp:

var fixedText = function(textbox, label) {
  var num = textbox.value.replace(/\D/g, ''); //non numeric
  num = num.substr(0, 10); //max 10 digits
  textbox.value = label + num;
};
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />

简单 label ,inputscript:

var numeric = function(textbox) {
  var num = textbox.value.replace(/\D/g, '');
  num = num.substr(0, 10);
  textbox.value = num;
};
label.partial,
input.partial {
  border: 1px ridge grey;
  margin-bottom: 3px;
}
label.partial {
  border-right: none;
  cursor: text;
}
input.partial {
  border-left: none;
  margin-left: -4px;
  top: -1px;
  position: relative;
}
<label for="PostalCode" class='partial'>Postal Code&nbsp;</label>
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />
<br/>
<label for="ContactNo" class='partial'>Contact No&nbsp;</label>
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />