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);
}
}
A single regular expression will easily perform this check :
/^ 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 :