0

while typing in an input, I want to validate the text character by character e.g text is: The Quick Brown Fox

I want to match character by character

like: initially, text box in empty:

I press

T => OK

h => OK

a => Not Ok (will not be written in the text)

e => OK

and so on

I've written this jquery regex expression. But, it's not working as it is comparing the whole text.

$("#text").on("keypress", function(e) {
    if (!(/^The Quick Brown Fox$/i.test($(this).val()+String.fromCharCode(e.keyCode)))) {
        return false;
    }
}
3
  • You are checking for each key press while your regex matches for the entire string. Check once the entire string has been entered. Commented May 5, 2014 at 6:14
  • You are specifically prepending the entire string ($(this).val()+) when you test. Commented May 5, 2014 at 6:16
  • Why not lookupString.indexOf($(this).val()) !== -1 instead? Commented May 5, 2014 at 6:19

4 Answers 4

2

you can try it like

$("#text").on("keypress", function(e) {

    var myText = ($(this).val()+String.fromCharCode(e.keyCode));

    if ('The Quick Brown Fox'.indexOf(myText) != 0) {
        return false;
    }

});

Here is a sample fiddle.

Sign up to request clarification or add additional context in comments.

Comments

1

The regex isn't the best choice for doing this kind of thing.

You'll be better off setting up a string and looping through characters, one-by-one until you find a mismatch.

Check the string, from the beginning, each time a key is hit. That catches people pasting into the input.

Comments

0

You are checking for each key press while your regex matches for the entire string. Check once the entire string has been entered.

$("#text").on("blur", function(e) {
    if (!(/^The Quick Brown Fox$/i.test($(this).val()))) {
        return false;
    }
}

1 Comment

But, I want to check while typing.. not after typing.
0

May be you can loop and compare character by character and do the processing.

HTML: Enter the Proper text:

JQUERY CODE:

    var txt = "The Quick Brown Fox";
    var index = 0;
    $("#text").on("keyup", function (e) {
          var st = $('#text').val();
          while (index < st.length) {
              if (txt[index] === st[index]) index++;
              else {
                  $(this).val(st.substr(0, index));
                  break;
              }
          }
    });

LIVE DEMO: http://jsfiddle.net/dreamweiver/2dadL/21/

Happy Coding :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.