Search code examples
javascriptvalidationkeypress

Javascript to validate only Numeric after predefined text in a textbox


I'm trying to use Javascript to make a textbox that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. I need to allow only 10 digit numeric after the readonly text and need to validate for the numeric digits. The following is the Javascript code for having the readonly in textbox

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;
}
});       

Solution

  • If you looking for solution with script then here is plain js and 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: ' />

    With simple label ,input and script:

    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' />