How to prevent a user from removing the first three characters in a text input?

Try this (it's not the best solution but it works):

Fiddle

$(document).ready(function() {
  $("#tb").on("keyup", function() {
    var value = $(this).val();
    $(this).val($(this).data("initial") + value.substring(3));
  });
});

Mind you that if I use my mouse to highlight the first 3 characters and move them at the end of the other texts, it won't complain and allow it which is not what you want.


Option 1 : Put the 3 character prefix outside of the input. This is the best from a user experience perspective.

<p>abc <input id="Lab" maxlength="10" name="LabWareId" type="text" class="valid"></p>

Option 2 : Check for backspace keypress and prevent the delete accordingly.

$(document).on('keydown', function (e) {
  if (e.keyCode == 8 && $('#Lab').is(":focus") && $('#Lab').val().length < 4) {
      e.preventDefault();
  }
});

I would probably put the 3 generated characters to the left of the input, so the user doesn't think those are editable. You can make this look kinda nice using bootstrap like so.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<label for="basic-url">Enter thingy:</label>
<div class="input-group">
  <span class="input-group-addon" id="basic-addon3">ABC</span>
  <input type="text" class="form-control" id="basic-url" aria-describedby="basic-addon3" maxlength="7" placeholder="Enter 7 characters">
</div>