Nikhil Surendran
Nikhil Surendran

Reputation: 1006

Checking for alphabet and numeric chars in a field

I am trying to write javascript code for making sure a field in my form has its first 2 characters as alphabets (US) and the rest 8 are numerics.

The total has to be 10, and if any of these are not satisfied, I should throw up an alert box.

I am checking for numerics now but I don't know how to combine checking for alphabets and numerics in the same field.

Here is my code for checking for numerics.

Please help me out! sid is my field name.

// only allow numbers to be entered
var checkOK = "0123456789";
var checkStr = document.forms[0].sid.value;
var allValid = true;
var allNum = "";

for (i = 0; i < checkStr.length; i++)
{
    ch = checkStr.charAt(i);
    for (j = 0; j < checkOK.length; j++)
        if (ch == checkOK.charAt(j))
            break;

    if (j == checkOK.length)
    {
        allValid = false;
        break;
        if (ch != ",")
            allNum += ch;
    }
    if (!allValid)
    {
        alert("Please enter only 8 numeric characters in the \"sid\" field.");
        return (false);
    }
}    

Upvotes: 1

Views: 3905

Answers (4)

Priyank Patel
Priyank Patel

Reputation: 6996

/^([a-zA-Z]{2}\d{8})$/; should check for 2 characters and then 8 decimals.

Upvotes: 0

st3inn
st3inn

Reputation: 1596

Simple regular expression, checks for 2 characters + 8 digits

var checkStr = document.forms[0].sid.value;
if (checkStr.match(/\b[A-z]{2}[0-9]{8}\b/) === null) {
    alert("Please enter only 8 numeric characters in the \"sid\" field.");
    return (false);
}

Upvotes: 0

Anoop
Anoop

Reputation: 23208

You can use regexp. jsfiddle

var regExp = /[a-z]{2}[0-9]{8}/i;

var text = 'ab12345678'; 
if(text .replace(/[a-z]{2}[0-9]{8}/i, "").length > 0){
    alert("Please enter only 8 numeric characters in the \"sid\" field.");
    return (false);
} 

Upvotes: 0

HBP
HBP

Reputation: 16033

A single regular expression will easily perform this check :

   /^[a-zA-Z]{2}\d{8}$/

/^ match beginning of string

[a-zA-Z]{2} match exactly 2 alphabetic characters

\d{8} match exactly 8 digits

$/ match end of string

Use as follows :

 /^[a-zA-Z]{2}\d{8}$/.test (str)   // Returns true or false

Upvotes: 5

Related Questions