0

I want to validate the string which the user enters into a textbox. I have to prevent user from entering alpha characters into the textbox and I also want to restrict user to entering no more than 6 digits, and also prevent the user from entering special characters into the textbox. I have tried the below code which is working when the user manually enters the value in textbox, but it's not working when the user pastes the some code into textbox.

<input type="text" name="textbox" id="textbox" class="form-control" required>

$("#textbox").on('keypress', function(e) {
        var length = 6;
        var validationtype = 'numeric';
        var stringLength = $('#textbox').val().length;
        if(stringLength < length) {
            if(validationtype == 'alphanumeric') {
                if (e.which != 8 && e.which != 0 && ((e.which < 65 || e.which > 122) || (e.which < 48 || e.which > 57))) {
                    return false;
                }
            } else if (validationtype == 'numeric') {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    return false;
                }
            }
        } else {
            return false;
        }
    });
kmoser
  • 8,780
  • 3
  • 24
  • 40
  • Please write complete code. Where is the otp_field coming from and what does it ? is it prefilled ? if you provide complete code it will easy to provide a quick solution – Mr Khan Nov 26 '20 at 05:36
  • i updated my code – suresh prajapati Nov 26 '20 at 05:39
  • 1
    I hope this answers your question : [check this](https://stackoverflow.com/a/28062842/6548185) – Sachin_1729 Nov 26 '20 at 05:46
  • Does this answer your question? [jquery keyup detect paste text from input](https://stackoverflow.com/questions/21642758/jquery-keyup-detect-paste-text-from-input) – kmoser Nov 26 '20 at 06:10

1 Answers1

0

Just use Paste event to handle this the same way.

/*Click and Past events*/
$("#textbox").on('keypress', function(e) {
  return onTextChange(e, this);
});

$("#textbox").on("paste", function(e){
  return onTextChange(e, this);
});
/*--------------------*/

function onTextChange(e, thisRef){
  let length = 6;
  let stringLength = $(thisRef).val().length;
  let validationtype = 'numeric';
  
  if(stringLength < length && e.which !== undefined) {
      if(validationtype == 'alphanumeric') {
          if (e.which != 8 && e.which != 0 && ((e.which < 65 || e.which > 122) || (e.which < 48 || e.which > 57))) {
              return false;
          }
      } else if (validationtype == 'numeric') {
          if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
             return false;
          }
      }
  } else {
      return false;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="textbox" id="textbox" class="form-control" required>
Mr Khan
  • 2,139
  • 1
  • 7
  • 22