Page is a not externally linkable
rewboss - 9:08 am on Jul 22, 2002 (gmt 0)
var myNumber=myString-0 (You can also multiply or divide by 1: but you can't add 0, because the + operator will convert the zero to the string "0" and then concatenate, effectively multiplying an integer by 10.) To convert a string to an integer, use parseInt(). This accepts a string, and returns as a number the left-most digits as far as the first character which is not a digit -- so parseInt('100 dollars') becomes the number 100, and parseInt('13.6') becomes 13. If the string does not start with a digit, the function will return NaN. Putting these things together, to test for an integer, use the following: if(parseInt(myValue)!=myValue-0) You need to check each field that requires an integer in this way. Text input field values are available to JavaScript as: document.formName.elementName.value where formName is the value of <form name="..."> and elementName is the value of <input name="..."> When I validate forms, I usually define an empty string called, perhaps, errmsg. Every time the script encounters an error, I add a description of the error to errmsg -- for example: if(parseInt(document.myForm.numUnits.value)!=document.myForm.numUnits.value-0) errmsg+='\nYou can only order a whole number of units'; At the end of the validation script, I test errmsg. If it contains the empty string, the form is correct (no errors) and can be submitted. Otherwise, it should display an error message and cancel the form submission process: if(errmsg=='') return true; This should be stored in a function called, say, check(). It is then invoked by the onsubmit() handler like this: <form name="myForm" onsubmit="return check();"> As a short cut you can use the this keyword: if you write the <form> tag like this: <form name="myForm" onsubmit="return check(this);"> "this" refers to the form. The function declaration can look like this: function check(f){ ... } ...and instead of document.myForm.numUnits.value you can write f.numUnits.value. You can't rely on client-side validation though, since you can't rely on JavaScript being enabled in the browser. It must be in addition to your server-side script. Look on it as an extra service for those fortunate enough to have JavaScript, not as a foolproof way to cut down on your server-side programming. If this post doesn't mean much to you, I'd advise you not to try it until you have got to grips with JavaScript. It's a tricky language, and if you get it slightly wrong it is worse than useless.
JavaScript is a very loosely-typed language, which means there is no way to cast variables -- not officially, at least. This is a problem, because form input values are read in as strings. However, you can force JavaScript to make the necessary conversion from string to number by simply subtracting zero:
alert('The form could not be submitted because it contained the following error(s):\n'+errmsg);
return false;