codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:



Home » Javascript » Article

Javascript Form Validation Function

Article by:  Jeff Anderson  ( 1362 ) (2/26/2002)
Bookmark us now! Add to Favourites
Email a friend!Tell a friend
Summary: A javascript validation function that you can use to validate all types of forms.
Viewed: 432175 times Rating (187 votes): 
 3.7 out of 5
 Rate this Article  Read Comments  Post Comments

In several other tutorials, we have looked at various functions to check aspects of form validation :

Here we are going to bring these all together, by writing a ValidateForm function that can call these, or other similar functions. You can then adapt this script to validate the particular fields you need in the way you require.

Ammend your <form> tag, so it looks something like this:


<form name=form1 action=address.asp method=post onsubmit="javascript:return ValidateForm(this)">



What the onsubmit method does here is waits for the results of the ValidateForm function. If it returns true, our validation has succeeded - the form entries are in an acceptable form. If it returns false, there has been an error, and the user will need to correct it before being allowed to submit the form. So now let's have a look at the ValidateForm function itself. Exactly how it will look of course will depend on the fields you need to validate.





function ValidateForm(form)
{
   if(IsEmpty(form.account_number))    {       alert('You have not entered an account number')       form.account_number.focus();       return false;    }    if (!IsNumeric(form.account_number.value))    {       alert('Please enter only numbers or decimal points in the account field')       form.account_number.focus();       return false;       } return true; }

To understand this function, remember that the return statement exits from the function and returns the code to the calling statement. Therefore, if the field 'IsEmpty', we alert the user, set the focus of the form to the appropriate field, and return false as the result. The calling statement reads the false value and does not submit the form. The user remains on the same page, with the focus pointing them to the error of their ways.

If however all the checks are verified, at the end of the ValidateForm function, we have a return true statement, meaning the form will submit successfully.







CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums
Rate this article:     Poor Excellent
View highlighted Comments
User Comments on 'Javascript Form Validation function'
Posted by :  Archive Import (Eva) at 22:48 on Wednesday, October 09, 2002
Very useful and simple code. Well documented how to use it.
Posted by :  Archive Import (bondawg3) at 01:13 on Saturday, December 07, 2002
Needs to show the complete code of the form it is validating.
Posted by :  Archive Import (Jean) at 15:47 on Monday, March 24, 2003
how about validating for all whitespaces in a text box like Comment box?
Posted by :  Archive Import (nieA) at 00:58 on Tuesday, April 22, 2003
what if i have 2 submit buttons in the form? calling a jsfunction on the onsubmit handler of the form element would cause other submit buttons to not work properly.
Posted by :  Archive Import (noman) at 10:39 on Monday, April 28, 2003
plz show the all code and how we use the email validation becoz u mentioned only to validation empty and numeric but where is email one

noman
Posted by :  Archive Import (soufia) at 17:55 on Saturday, May 03, 2003
help me out
form.account_number.focus(); is bringing the focus back to this text field .. right? but wats the
pupose of return false; ?? i forgot plz if any one could help me on this...
Posted by :  Archive Import (modeler4) at 13:30 on Thursday, May 15, 2003
back to soufia:
return false is, in effect, saying that there was a "mistake", so let the user correct it, you either return true if everything is Ok, or return false if something turns out to not be valid.
Posted by :  Archive Import (Laura) at 16:23 on Tuesday, June 10, 2003
A printable version of this would really help me :(
Posted by :  Archive Import (my_name_is_unknown) at 16:15 on Sunday, July 20, 2003
i like it
Posted by :  jackiew at 10:42 on Friday, November 14, 2003
Ok, I'm lost. I can't get this to work. I know I'm missing something small and I'm really hoping one of you can find it.

My script reads:


</HEAD>
<script>
function ValidateForm(TrifoldOrder)
{
   if(IsEmpty(TrifoldOrder.Quantity))
   {
      alert('You have not entered a quantity to be ordered. Orders are in increments of 100.')
      TrifoldOrder.Quantity.focus();
      return false;
   }
}
return true;
}
</script>

<BODY bgcolor="#000056" link="#000056" vlink="#000080" alink="#800000">



and my form tag reads:

<form name="TrifoldOrder" method="post" action="trifoldorder.asp?post=yes" onsubmit="javascript:return ValidateForm(TrifoldOrder)">


What am I doing wrong?

Help!
Jackie
Posted by :  litu at 01:28 on Friday, December 05, 2003
try this out

<form name="TrifoldOrder" method="post" action="trifoldorder.asp?post=yes" onsubmit="javascript:return ValidateForm(this)">
Posted by :  benzo at 04:53 on Tuesday, March 09, 2004
test
Posted by :  bitsnz at 03:21 on Thursday, March 11, 2004
Im in a situation where once the validation is true, user data that has been entered must get sent to an xml file on the server for storage. This is no problem BUT once the user enters the data and clicks a button they must be sent to a pay site (ogone) to enter payment details etc. The code to save the data in an xml file is ASP code and ive read that you cant call an ASP function from within javascript (within the validation code). so how can i capture the data (behind the scenes so to speak) while the user gets directed to the pay site?

Posted by :  Boogalou at 08:13 on Friday, April 02, 2004
Is there any way to make this into a password login? One that doesn't show on view source!
Posted by :  pk_on_net at 21:37 on Tuesday, September 28, 2004
Hello,
You may try this.

<form name="TrifoldOrder" method="post" action="trifoldorder.asp?post=yes" onsubmit="javascript:return ValidateForm(document.TrifoldOrder)">
Posted by :  yguyon at 17:09 on Thursday, October 07, 2004
I need help with this.

I have three text field that accept data. The sum of two text field value can't be greater than my third text field.

Any function in Java script?
Posted by :  maynard49 at 17:39 on Saturday, February 25, 2006
Hi there im trying to create a script so that the form automatically corrects the entry that a user enters. so each entry it would automatically correct the letters. like to auto capitalize the first letter for the user..

thanks

doug
Posted by :  scohie at 00:34 on Sunday, January 28, 2007
Please help me to include email validation in this script,(cant work it out from the example, dumb I know). Also to verify if a radio box has been checked.

Thanks

<Added>

I'm sorry I should have said 'radio button', not 'radio box' I think I've lost it completely!
Posted by :  ray2007 at 06:08 on Monday, August 27, 2007
I LIKE IT
Posted by :  gaya3 at 02:47 on Friday, September 21, 2007
javascript validation for not allowing any char,special char,space,tab,it should allow only numbers,decimal.
Posted by :  saghi at 07:48 on Wednesday, November 07, 2007
Hi.I want to complete a form that has some fields.(this is similar your join form).The necessary fields in this form must be fill with user's information.if they don't fill these fields and press submit key,they will see an Error Message in this form and return to same page.(Exactly your join form).

plese help me and give me functions.
thanks alot
Best Regards.
Posted by :  robinsridhar at 06:29 on Saturday, June 28, 2008
sorry,

I do not have any comment for this.

Posted by :  tnc2228 at 19:49 on Tuesday, January 13, 2009
hello,

how can i control the null in the forms
ex:
username: "there is textfield"
password: "there is textfield"

when i enter username nothing and pass to password field then i have to get an messege like :
"username didn't entered !"

how can i write this ?

pls help me.. thx!!
Posted by :  Mei at 09:13 on Monday, March 23, 2009
Thanks that’s what I was looking for. But I have I question, as you now if it’s false it will show a screen that said the message. But I don’t want to do that, I want that below the each form, when it’s false it show a message in red. How can I do that?

Thanks
Posted by :  nancy16788 at 09:14 on Thursday, October 08, 2009
how to validate a function....i am doing a casestudy on "birds in different countries"....
i provided a text box and i need to SEARCH the birds detail if i give the name of a bird....help me please


To post comments you need to become a member. If you are already a member, please log in .

 



RELATED ARTICLES
Javascript - Enable and Disable form elements
by Jeff Anderson
This is a relatively little known and under-used feature of javascript which can be very useful in guiding a user through a form. Using the disabled tag, you can switch on and off elements in a form.
Check IsNumeric Function
by Jeff Anderson
A javascript validation function to check whether the details entered by a user are numeric.
Javascript Onload Event
by Jeff Anderson
Sometimes you need to perform an action immediatley after the page has loaded. That's when the onLoad Event Handler comes in handy
Form Validation Function
by Jeff Anderson
A javascript validation function that you can use to validate all types of forms.
JavaScript Field Is Empty Form Validation
by Jeff Anderson
This javascript function allows you to check whether a form field has been completed or not.
Javascript Get Selected Text
by Jeff Anderson
A cross-browser script to get text selected by the user
Check Email Validation Function
by Jeff Anderson
A javascript validation function to check whether the user has entered a valid email address in a form.
Multiple submit buttons on a single form
by Kiran Pai
This script shows you how to submit the contents of a form to different programs depending on which Submit button you press. Additionally it also shows how to call two different functions when you press the Submit button.
Validate Form and Disable Submit Button
by Marylou Marks
I have a form that validates info, but I also want to disable the submit button. The disable part worked before adding the form validating.
Javascript onUnload Event Handler
by Jeff Anderson
The onUnload Event Handler allows you to perform an action as the user leaves the page.








Recent Forum Threads
• Significant Factors
• Perl array access
• Re: huffman encoding and decoding in C++...
• Perl One Liner: Replace {(
• Re: html including php, accessing the functions
• Something like an INI editor or a DelimitedText-Editor
• Error Deleting File or Folder
• Re: How can use ASP.NET RegularExpressionValidator for alphanumeric 10 digit input
• Re: drop-down menu selected value


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2009