Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » How do I » Client Side Validation with JavaScript in ASP.NET

Client Side Validation with JavaScript in ASP.NET

This simple program will guide how to do client side validation in JavaScript.

Technologies: ASP.NET 1.0,Visual C# .NET
Total downloads :
Total page views :  186668
Rating :
 4.16/5
This article has been rated :  19 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor



This simple program will guide how to do client side validation of Form in JavaScript.

In this just make a form as follows:

  1. Name : <asp:TextBox ID="txtName" />
  2. Email : <asp:TextBox ID="txtEmail" />
  3. Web URL : <asp:TextBox ID="txtWebUrl" />
  4. Zip : <asp:TextBox ID="txtZip" />
  5. <asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server" Text="Submit" />

Now on the source code of this form in script tag write the following code:

<script language="javascript" type="text/javascript">
function
validate()
{
      if (document.getElementById("<%=txtName.ClientID%>").value==""
)
      {
                 alert("Name Feild can not be blank"
);
                 document.getElementById(
"<%=txtName.ClientID%>"
).focus();
                 return false
;
      }
      if(document.getElementById("<%=txtEmail.ClientID %>").value==""
)
      {
                 alert(
"Email id can not be blank"
);
                document.getElementById("<%=txtEmail.ClientID %>"
).focus();
                return false
;
      }
     var
emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
     var emailid=document.getElementById("<%=txtEmail.ClientID %>"
).value;
     var
matchArray = emailid.match(emailPat);
     if (matchArray == null
)
    {
               alert(
"Your email address seems incorrect. Please try again."
);
               document.getElementById(
"<%=txtEmail.ClientID %>"
).focus();
               return false
;
    }
    if(document.getElementById("<%=txtWebURL.ClientID %>").value==""
)
    {
               alert(
"Web URL can not be blank"
);
               document.getElementById(
"<%=txtWebURL.ClientID %>").value=
"http://"
               document.getElementById("<%=txtWebURL.ClientID %>"
).focus();
               return false
;
    }
    var Url=
"^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
    var tempURL=document.getElementById("<%=txtWebURL.ClientID%>"
).value;
    var
matchURL=tempURL.match(Url);
     if(matchURL==null
)
     {
               alert(
"Web URL does not look valid"
);
               document.getElementById(
"<%=txtWebURL.ClientID %>"
).focus();
               return false
;
     }
     if (document.getElementById("<%=txtZIP.ClientID%>").value==""
)
     {
               alert(
"Zip Code is not valid"
);
               document.getElementById(
"<%=txtZIP.ClientID%>"
).focus();
               return false
;
     }
     var digits="0123456789"
;
     var
temp;
     for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>"
).value.length;i++)
     {
               temp=document.getElementById(
"<%=txtZIP.ClientID%>"
).value.substring(i,i+1);
               if
(digits.indexOf(temp)==-1)
               {
                        alert(
"Please enter correct zip code"
);
                        document.getElementById(
"<%=txtZIP.ClientID%>"
).focus();
                        return false
;
               }
     }
     return true
;
}
</script>

And in code behind file just write the below code.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
               btnSubmit.Attributes.Add(
"onclick", "return validate()"
)
End Sub

Now you will get a form with proper validation.

I hope this is going to help you.


Login to add your contents and source code to this article
 Article Extensions
Contents added by JIGNESH prajapati on Jul 29, 2009
 [Top] Rate this article
 About the author
 
Puran Kaushal
Puran Chand Kaushal is working with .NET technology. PCK background includes Master's in Computer Science and Applications . Currently he is exploring C#, ASP.NET, WCF,Design Patterns and SOA.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Article helped me a lot by Abdul On May 20, 2006

Hi Puran,

I would like to thank you for your article. It really helped me a lot in doing validation. I learned a lot from that article.

I will contact you further if I have any doubts.

Regards,

Abdul Sami

sami@gotouchpoint.com

 

 

Reply | Email | Delete | Modify | 
Thanks by Vinay On May 23, 2006

Thanks Mr purankaushal

ur aritical is very helpfull , thanks a lots,please also give the idea  how to use error provider in java script in web pages rather than message box for error message

 

Regards,
For Oriensoft Technologies Pvt. Ltd.

Vinay Patel
Software Programmer
E-mail :-
vinayp@oriensoft.com
Tel: +91-22-67111555  Fax: +91-22-67111666
24 x 7 Support & Sales Toll Free : 1-800-22-5171 (India Only)
Web :
http://www.oriensoft.com

 

Reply | Email | Delete | Modify | 
Thanx.....and need help again... by Aditya On October 10, 2006

Hello Sir,

      Thanx for your validataion with javascript article....that was realy helpfull.......Thanx.

 

   Sir, I want to know about ajax....Will you plz. put a realtime small example of ajax...Thanx and bye...

Reply | Email | Delete | Modify | 
Re: Thanx.....and need help again... by Puran On January 30, 2007

hi

what short of help you need from me just send me the detail

regards

puran

Reply | Email | Delete | Modify | 
have a prob by Neeraj On November 21, 2006
where i have to put the script tag,in HEAD tag or in BODy tag,plz help me, i need it very badly..
Reply | Email | Delete | Modify | 
Re: have a prob by Puran On January 30, 2007

Hi Neeraj

You can put script tag any where in Body or in Head

But w3 form recomand us to put the tag in head

Regards

Puran

 

 

Reply | Email | Delete | Modify | 
Re: have a prob by Yuvraj On January 29, 2008
in Head tag
Reply | Email | Delete | Modify | 
Re: Re: have a prob by Yuvraj On January 29, 2008
thanx
Reply | Email | Delete | Modify | 
Re: Re: Re: have a prob by Yuvraj On January 30, 2008
Good one
Reply | Email | Delete | Modify | 
Re: have a prob by Yuvraj On January 29, 2008
good
Reply | Email | Delete | Modify | 
good by karthick On March 21, 2007
dood
Reply | Email | Delete | Modify | 
.how to use document.getElementById for radi uttons by anju On March 22, 2007
hi.. I have two radio buttons on my form n a Report button. On report button click i have 2 check which button is clicked and accordingly open th report. I m confused how 2 do this using document.getElementById on code behind to check. As it needs two clicks to open up the report.
Reply | Email | Delete | Modify | 
JavaScript Validation in asp.net by Abdullah On April 11, 2007
Hello Puran, thank you so much for the article. After I paste the code in the code behind file as you've instructed, i get this error: Name "btnSubmit" is not declared. Please how can I go about fixing this problem. Thanks
Reply | Email | Delete | Modify | 
hi help me by alex On April 27, 2007
hi document.getElementById("<%=txtWebURL.ClientID%>"). and document.getElementById("txtPostalcode").value both are used to retrive values from aspx then pls tel me the diff betwen them quick pls
Reply | Email | Delete | Modify | 
help me by alex On April 27, 2007
hi document.getElementById("<%=txtZIP.ClientID%>") and document.getElementById("txtPostalcode").value both are used to retrive values from aspx page then pls tel me the diff betwen them quick pls
Reply | Email | Delete | Modify | 
thanks a zillion by Himani On May 29, 2007
yours was the only blog that solved my query of accessing the asp.net textbox controls through javascript. i was unable to retreve them using document.getelementbyid() until u suggested a differnet way ("<%=txtZIP.ClientID%>"). truly useful thanks
Reply | Email | Delete | Modify | 
thanks ... can you help with Canadian postal code by lance On July 10, 2007

Thanks for sharing this excellent code. Although it may be obvious to most I’m not sure how you did the email verification.

Could you please explain this line of code for me?

 /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;

I can tell that before the @ sign you accept all upper and lower case letters but what do the rest of the symbols represent.

Also I’m from Canada and our postal code is 6 characters long but alternate

Letter Number Letter Number Letter Number

Any Ideas on how to validate for this?

Reply | Email | Delete | Modify | 
I would like to know if this would work for asp.net 2.0? by Ben On August 6, 2007

I would like to know if this code works for asp.net 2.0 ? I am trying to implement this code to my website but is not working with asp.net 2.0

Is this for asp.net 2.0 or 1.0 anyway?

Reply | Email | Delete | Modify | 
Re: I would like to know if this would work for asp.net 2.0? by Puran On August 10, 2007

Hi

This whole code is written in VS2005.

This whole code will also work in VS2003

 

Regards

Puran

 

Reply | Email | Delete | Modify | 
abt blocking of Jscript by Jyothirmai On September 5, 2007
wot happens to this client side validator if we block Javascript?
Reply | Email | Delete | Modify | 
ajax by jatin On September 12, 2007
how to use ajx in asp.net
Reply | Email | Delete | Modify | 
having a problem by Manga On September 26, 2007

Hi puran, i would like to validate the email id a@a.com but it is not accepting the validation .if there are 2 characters before the "@ "it is valdating but if i have 1 character it is not validating.

Thanks in Advance

 

Regards

kanth

Reply | Email | Delete | Modify | 
Re: having a problem by Puran On October 1, 2007

Just Change Reg ex to 2 instead of 3

 

Regards

Puran

Reply | Email | Delete | Modify | 
Re: Re: having a problem by badari On December 18, 2007
if i didn't enter any value in texbox the curser should not move to next textbox and its shold disaply alert and when i have enterd the value the cursor can move to the next textbox Please give me answer quickly
Reply | Email | Delete | Modify | 
What if.. by Mohammad On December 22, 2007
What if i have a delegate ' server side ' on the same button, it shouldn't be called unless the validation returns true?!
Reply | Email | Delete | Modify | 
Hi Puran Can you solve my query by Deepak On January 7, 2008
I have text box which carries Postal Code and this text box is validated by a reg ex validator. Now I have State Drop down box. When I change the state in drop down box I need to revalidate the postal code text box using that .net reg ex validator. Now here my question is how can I handle such scenario. Please me the solution if any. Deepak Gupta
Reply | Email | Delete | Modify | 
really exlent by sreekanth On January 9, 2008
hi this is sreekanth this articale is really exlet i hope i am expecting meny more articales like this form u Thanks & Regards Sreekanth Kolluri Software Engineer(.Net) NETSOFT INFORMATICS Pvt Ltd. SCO 441-442, Sector 35-C, Chandigarh (UT) 160022 India Email | sreekanth.kolluri@netsoftglobal.com Voice | 91-172-264-6460, 266-2464 [Board] Fax | 91-172-2646461 [ India ] +1-419-745-0256 [US] Web | www.netsoftglobal.com
Reply | Email | Delete | Modify | 
Thankz Friend!!!!! by muthu On January 29, 2008
var emailRegExp = /^[a-z][a-z_0-9\.]*[a-z0-9]+@[a-z0-9]+[a-z_0-9\.]*[a-z0-9]+\.[a-z]{2,4}$/i. using this kind of regex
Reply | Email | Delete | Modify | 
hide/ unhide text block by Yuvraj On January 30, 2008
how to hide a block of text after clicking on image at client side like what happens in this same page when i click on '?' button all the data below that goes up & vice versa
Reply | Email | Delete | Modify | 
ASP.Net + javascript by Nag On February 26, 2008
I want an image to be displayed only when summary validator shows an error. if there is no errormessage shown summary validator the image should be invisible.Please help me.(Every thing i want it to happen at client side only.....if no errors i want server even to be raised) thanks Vardhan vardhan_babu@yahoo.com
Reply | Email | Delete | Modify | 
validation not working in content page if...... by Manoj On March 3, 2008
Thnx for ur article. But there is a problem actually whenever i'm putting my code in jsfile and it's path in master page then this article is not working properly.........plz help me......
Reply | Email | Delete | Modify | 
Need a help by Rahul On March 3, 2008
i have to validate ftp server path, below are valid paths 1) ftp:\\10.11.16.32\CDR 2) 120.11.25.154 3) ftp.worldroam.uk.co.in 4)c:\\CDR\Test can any one provide a regular expression which will work for me all above 4 states. thanks in advance.
Reply | Email | Delete | Modify | 
help by namita On March 6, 2008
pleas give me javascript validation with c# .net code for phone number.
Reply | Email | Delete | Modify | 
validation for check box by kiran On March 22, 2008
how to validate checkbox is it checked or not by using java script for client side scripting.
Reply | Email | Delete | Modify | 
control collection can not be modified by Babak On August 13, 2008
System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>). I get the above error when attempting to use similar code: I have code as shown: function ValidateEntry() { var PONum1; PONum1 = document.getElementById('<%= PONum1.ClientID %>'); ... } ... In my code behind page Page_Load event, I use this code: btnSubmit.Attributes.Add("onclick", "return ValidateEntry();"); I don't know why I am getting the error. Please help.
Reply | Email | Delete | Modify | 
Re: control collection can not be modified by Puran On August 14, 2008

Can you send me code of your problem.

Regards

 

Puran

Reply | Email | Delete | Modify | 
Great Article by Robert On November 1, 2008
Can you tell me how to pass arguments into a function using this technique. For instance I have a function that takes a number of the form elements as arguments. Submit.Attributes.Add("onclick", "return IsValidCreditCard(txtCCNumber, txtCCType,cboExpiresDateMonth, cboExpiresDateYear, txtCCCode)") Where txtCCNumber, txtCCType etc. are a values from the froms collection? thanks
Reply | Email | Delete | Modify | 
Best article for validations by Naresh On November 3, 2008
Hi Puran, Thanks Puran for ur article on Validations.You have covered almost all types of validations and gave us a good resource for me and to all the developers.Thanks again Puran.
Reply | Email | Delete | Modify | 
Re: Best article for validations by Puran On November 7, 2008
thnaks
Reply | Email | Delete | Modify | 
ASP.NET With C# Application by pappu On November 7, 2008
where i have to put the script tag,in HEAD tag or in BODy tag,plz help me, i need it very badly.. and what is use of global.asax and how it use it in my application.... regard pappu
Reply | Email | Delete | Modify | 
Re: ASP.NET With C# Application by Puran On November 7, 2008
Thanks
Reply | Email | Delete | Modify | 
Re: ASP.NET With C# Application by Puran On November 7, 2008

put script tag in head

global asax file is used to declare application events and variables

 

 

Reply | Email | Delete | Modify | 
ASP.NET by pappu On November 7, 2008
how is run the script in database
Reply | Email | Delete | Modify | 
Re: ASP.NET by Puran On November 18, 2008

we can not run javascript on database

Regards

Puran

Reply | Email | Delete | Modify | 
doubt by niaz On January 4, 2009
sir can u explain this sentence briefly (document.getElementById("<%=txtName.ClientID%>").value=="") and sir what do u meant by" ispostback"?
Reply | Email | Delete | Modify | 
Thanks by kalandi On February 8, 2009
Hi Puran, Thanks a lot for your article which helped me a lot for my validation problem.Its really amazing. Regards Kalandi Charan Acharya kalindii_orr@yahoo.co.in
Reply | Email | Delete | Modify | 
How to use javascript validation with Ajax Update Panel and Master Page by Muskan On March 12, 2009
Hello Puran, Thanks for this article. This is really very helpful. But I have some problem while using it with Ajax Update Panel and Master Page. I am working on Asp.net 3.5 and I am trying to do the same things on a content page which is having a Master page, Ajax Update Panel and Script manager. The error is 'Object Required' Can you please help me if you have anything regarding this. I can send you the code if you want. Any help will be highly appreciated. Thanks
Reply | Email | Delete | Modify | 
asp.net validation in firefox when uaing ajax by anil On March 20, 2009
how to use required field validation and regular expression when using ajax modelpopup extenter with browser firefox
Reply | Email | Delete | Modify | 
how to implement client side validation with html control by chandana On June 1, 2009
thanx for the code. very helpful for me. but if i use html control instead of asp control then how should i implement it.

please mail me at chandana_13apr@yahoo.co.in

chandana


Reply | Email | Delete | Modify | 
Re: how to implement client side validation with html control by Puran On June 2, 2009
Hi
There is no change in code.YOu just make that html contol run at server.
Regards
Puran Kaushal
Reply | Email | Delete | Modify | 
The code is not working in IE. it is fine for firefox by Joanne On July 14, 2009
in IE, it still submit. How can I fix the problem. Thank you.
Reply | Email | Delete | Modify | 
Re: The code is not working in IE. it is fine for firefox by Puran On July 20, 2009
I have written this code for IE as well as Firefox
Regards
Puran
Reply | Email | Delete | Modify | 
Re: Re: The code is not working in IE. it is fine for firefox by Joanne On July 31, 2009
I am a newer for ASP.NET.

I follow the article to create a form. It is fine when run in firefox. but when I run it in IE, when the enter data is invalidate, it still submit which means run the code behind file (btnSubmit_Click()).

The code behind file like below. whatever the page is valid or not, it still go to updating the database.

Private Sub btnSubmit_click(...)
   If Page.IsValid Then
      update database...
   Else
     return
   End If
End Sub

what'w wrong with my code?

Thank you.
Reply | Email | Delete | Modify | 
Re: Re: Re: The code is not working in IE. it is fine for firefox by Puran On September 24, 2009
Hi
Please copy the code as it is .I have tested that code in IE as well as firefox.If you still face any problem please let us know.

Regards
Puran Kaushal
Reply | Email | Delete | Modify | 
comment by habib On September 14, 2009
nice way to explaine

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved