views:

74

answers:

3

Hi, I am using following code snippet, but its not working :-(

    //First four characters of input Text should be ALPHABATES (Letters)

    if (($("#txtId").val()).length >= 4) {
        var firstFourChars = $("#txtId").val().substring(0, 4);
        var pattern = new RegExp('[^A-Z]');

        if (firstFourChars.match(pattern))
            isValid = true;
        else
            isValid = false;
    }
+8  A: 

change /[^A-Z]/ to /^[A-Z]/

example :

var a = "ABCJabcd";
console.log(a.match(/^[A-Z]{4}/));
Ninja Dude
Thanks, Its working fine now :-).
Biki
A: 

The regex should be /[^A-Z]{4}/ if you want to match the 4 lowercase characters.

boxoft
+1  A: 

Hi, you don't need to use substring(). Your regexp can do all the work for you. The RegExp you are using matches against characters that are NOT between A and Z. As Avinash said, ^[A-Z]{4} will match if your first 4 characters are uppercase. "^" at the beginning of your regexp tells that the following should be the beginning of the string. When placed inside square brackets, it reverts the range of characters you want to match.

PJP
Thanks for the detailed explanation. :-)
Biki
If possible let me know its better to validate the above, either onblur event or onkeyupv event? I found, onkeyup fires on every character entered, but more consistent then onblur.
Biki
It depends on the behaviour you want to achieve: as you said, keyup is fired on each keystroke, and blur is fired only when the focus leaves the field.
PJP