I have a page that accepts input from many textboxes. Many of the
textboxes are intended to accept dates and times, thus, I expect only
digits to be entered. I originally tested using parseInt and isNaN, but
I'm not even sure that the results are as perfect as I need. I am
expecting to use RegExp.test(str ing), but I'm not 100% sure about that,
either.
Here is a test program with a textbox that has a maxlength of 2
characters. The function evaluateIt() measures the string for length.
If 2 characters, it tests against the regular expression \d\d. If 1
character, it tests against \d. This seems to be effective, but isn't
there a way to check either of these cases with one test? I tried
if(test(oneDig) || test(twoDig)), but this will allow a string of 1
digit and one non-digit to pass.
Here is the test program as I wrote it.
<HTML>
<HEAD><TITLE>Ex perimenting with regular expressions and the RegExp
object</TITLE>
<SCRIPT language="javas cript">
function evaluateIt(sent String)
{
twoDig = new RegExp("\\d\\d" ,"g");
oneDig = new RegExp("\\d","g ");
if(sentString.l ength == 2)
{
if(twoDig.test( sentString))
{
alert("Two digits. All good.");
return;
}
else
{
alert("Two digits. Not good.");
return
}
} //closes if length==2
if(sentString.l ength == 1)
{
if(oneDig.test( sentString))
{
alert("One digit. All good.");
return;
}
else
{
alert("One digit. Not good.");
return;
}
} //closes if length==1
alert("Neither 1 nor 2 digits. Not good.");
return;
} //closes evaluateIt function
</SCRIPT>
</HEAD>
<BODY>
<FORM action="nothing .htm" method=POST>
<BR><BR>
Type something in the box to check against a regular expression
<INPUT type=text size=2 maxlength=2 name="thebox">< BR><BR>
<INPUT type=submit value="Do It"
onclick="evalua teIt(thebox.val ue);return false;">
</FORM>
</BODY>
</HTML>