Simpleton’s JavaScript to Validate Forms

Suppose you want to check whether a entered value is numeric and need to proceed processing the form only if valid :

<script type=”text/javascript”>
function notEmpty(){
if(myTextField.value == “” || parseFloat(myTextField)==0){
alert(“Enter a valid numeric price”);
return false;

and the approximately corresponding HTML part :

<form id=”formone” name=”formone” method=”POST” action=”processor.php” onsubmit=’return notEmpty(this);’>
<input name=”TextInput_Element_ID” type=”float” id=”TextInput_Element_ID” />
<input name=”Submit” type=”submit” value=”Submit” />

The parseFloat() JS function converts a string into corresponding numeric value. If the string is not a valid number specifier, it returns NaN. To check this, the isNaN() function is used.

The processing MUST be done on the <form>’s onclick event rather than the Submit button’s onclick, if the latter is followed the form will be processed even if the function return false.


~ by toolweb on January 15, 2009.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: