Search code examples
jqueryregexonkeypress

I have a text field, which will accept only the NEXT TO NEXT ALPHANUMERIC that is single alphabet next is single numeric FOR EXAMPLE:- s3f4G5A2s3


javascript:

script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"

$(document).ready(function()

{

$(function(){

$('#custom_Expression').keypress(function(e){

var txt = String.fromCharCode(e.which);

console.log(txt + ' : ' + e.which);

if(!txt.match(/^([a-zA-Z][0-9]){3}$/g))

            {
                return false;
            }
        });
});

input type="text" id="custom_expression"


Solution

  • To allow single alphabet followed by single numeric, one or more times won't need + after [A-Za-z] and [0-9]. Most cases , anchors are necessary while validating strings. ^ asserts that we are at the start, $ asserts that we are at the end.

    var re= /^([a-zA-Z][0-9])+$/g;
    

    + repeats the previous token one or more times.

    OR

    var re= /^([a-zA-Z][0-9]){3}$/g;
    

    repitition quantifier {3} repeats the previous token exactly 3 times.