dominoGuru.com
Your Development & Design Resource
Quick-Tip: Javascript Validation - String Comparisons
02/14/2006 04:12 PM by Chris Toohey
Just a quick one for today - really busy with several items!
I was recently running into an issue with my one of my HTML-based form's Javascript data validation. And I could have kicked myself when I found the issue. Here's an example of my form:
...
function checksub(val) {
if (val == "99")
{ return false; }
}
....
<form onsubmit="return checksub(document.getElementById('test').value);"
...>
<input type="text" name="test" id="test" value=99 />
...
The above example would return True
, of course, because the
value of the test field is actually numeric 99 and not the
string 99. To solve this, and any possible potential future occurances
of such non-string datatypes making their way into my function, I modified it
to the following:
...
function checksub(val) {
val += "";
if (val == "99")
{ return false; }
}
....
<form onsubmit="return checksub(document.getElementById('test').value);"
...>
<input type="text" name="test" id="test" value=99 />
...
This adds a blank string to the value of val
, thus changing the
datatype and allowing me to return False
as I intended!