Tehreem
Tehreem

Reputation: 476

How to replace only current wrong character on keyup for regex?

I wish to replace any character not in the passport format(A9999999) from my input text. I have written the following (jsfiddle here):

HTML

Doc Type <input id='docType' value = 'PASS'/> <br>
Doc ID <input id='docId'/>

JS:

$(document).ready(function () {
    var docTypeVal = $("#docType").val();
    $('#docId').keyup(function() {
        if(docTypeVal == "PASS") {
            var $th = $(this);
            $th.attr("maxlength","8");

            if($th.val().length <= 1) {
                $th.val().replace(/[^a-zA-Z]/g, function(str) { 
                    alert('You typed " ' + str + ' ".\n\nPlease use correct format.'); 
                    return ''; 
                })
            }
            else if($th.val().length <= 8 && $th.val().length > 1) {
                $th.val().replace(/^(?!.*^([a-zA-Z]){1}([0-9]){7}$)/, function(str) { 
                    alert('You typed " ' + str + ' ".\n\nPlease use correct format.'); 
                    return ''; 
                })
            }
        }
    });
});

However, firstly, this doesn't replace any characters (wrong/right). Secondly, it gives the alert the moment I enter 2nd character onwards. It should accept the 1st char if it is alphabet (replace otherwise), from 2nd till 8th char it should accept only numbers (replace otherwise).

Upvotes: 1

Views: 444

Answers (2)

Tehreem
Tehreem

Reputation: 476

Fiddle Demo

Referred the JS of Twisty's and realized it should be as shown below:

if(docTypeVal == "PASS") {
  $(this).attr("maxlength","8");
  var term = $(this).val();
  var re = /^[a-zA-Z]{1}\d{0,7}$/i;
  if (re.test(term)) {
      $(this).removeClass("invalid");
      return true;
    } else {
      $(this).addClass("invalid");
      $(this).val(term.replace(term.charAt(term.length-1), 
      function(str) { 
      alert('You typed " ' + str + ' ".\n\nPlease use correct format.'); 
      return ''; 
    }));
    return false;
   }
 }

Upvotes: 1

Twisty
Twisty

Reputation: 30893

You can test this with 1 Regular Expression.

/^[a-z]?\d{0,7}$/i

This pattern will look A9 up to A9999999. It will fail on AA or 99.

Example: https://jsfiddle.net/Twisty/awL0onjg/20/

JavaScript

$(function() {
  var docTypeVal = $("#docType").val();
  $('#docId').keyup(function(e) {
    var exc = [
      11, // Tab
      127, // Del
    ];
    if (exc.indexOf(e.which) > -1) {
      return true;
    }
    var term = $(this).val();
    var re = /^[a-z]?\d{0,7}$/i;

    console.log("Testing:", term, re.test(term));
    if (re.test(term)) {
      $(this).removeClass("invalid");
      return true;
    } else {
      $(this).addClass("invalid");
    }
  });
});

Consider using .keydown() if you want to prevent the User from typing outside of that pattern. See More.

Upvotes: 1

Related Questions