Gabrielle-M
Gabrielle-M

Reputation: 1077

How can validate first alpha than numeric in jquery

I have write a validate rules in jquery which check only digits, now i want to add new validation rules is that first three digit alpha then 6 digit numeric in jquery. How can i do this. here is my only digits validation code here.

$(".mrn").keypress(function (e) {
 //if the letter is not digit then display error and don't type anything
 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
           return false;
}

Upvotes: 0

Views: 95

Answers (1)

Ghlen
Ghlen

Reputation: 659

I think it is unwise to check as the buttons are pressed whether or not the character pressed is valid. It's better to just check once when the user is done typing and leaves the DOMElement:

$(".mrn").focusout(function()
{
    //Assuming the .mnr class is also the textbox:
    var input = $(this).val();
    var regex = /^\w{3}\d{6}$/; //match against the described pattern.
    if (!regex.test(input)) {
       $("#errmsg").html("Digits Only").show().fadeOut("slow");
       return false;
    }
    return true;
});

This way the user can make typos and correct it themselves, there is much less code needed to maintain the logic and performance is a bit better tuned.

Upvotes: 1

Related Questions