asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Servers-Side Validations on the Client Side
By Pandurang Nayak
Rating: 2.8 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    A technique that can be used for executing server-side script from the client side and returning a JavaScript output from the server code is explained here.

    Let us take an instance of where this can be used. Many sites have user registration forms where the user is asked to choose a username and password. Obviously this user login has to be unique and so the required validation has to be done to make sure that the user login is not already present in the database. This makes a server round-trip inevitable and hence will need the user to have one extra step in the registration process, where he needs to change his login name.

    Trying to bring this on the client side would mean that a JavaScript validation has to be done, but it is definitely not a viable solution, because by just viewing the source code, the user is able to see all existing login names in the database.

    We look at this method by which we validate whether a username already exists in the database. Though this method is also not security-proof and leaks out the usernames (we will see how later), this demonstrates a powerful way of utilizing the concept in scenarios where security is not highly important, like an intranet.

    Remote JavaScript

    Remote JavaScript is basically putting all your JavaScript code in a .js file and using the SRC attribute of the SCRIPT tag to call this file in your HTML page. Again, you may think how does this solve the problem? The .js file needs to pick the user names from the database and if somebody does type the .js file's URL directly, will he still not be able to see all the user logins?

    Here is where the server side programming techniques of ASP come into play. For further explanation, let me take a sample form. This form is a HTML page that needs to take a preferred login from the user.

    The HTML source code for this file (say login.htm) would be:

    
    <FORM ACTION= "submitlogin.asp" METHOD=POST NAME= "loginform">
    <p>Enter preferred user login: <INPUT TYPE= "text" NAME= "userlogin" VALUE= ""><BR>
    <P>Enter a password : <INPUT TYPE= "password" NAME= "userpass" VALUE= ""><BR>
    <P><INPUT TYPE="SUBMIT" NAME="SUBMIT" VALUE="SUBMIT">
    </FORM>
    
    
    Now include the following code in the HEAD of the HTML file.
    
    <SCRIPT LANGUAGE="JavaScript" SRC="checkusers.asp">
    
    
    Look at how the SRC attribute which conventionally refers to a .js file, is referring to a .asp file. Let us now take a look at this approach. The HTML file would expect checkusers.asp to be a file that contains JavaScript in the application/x-javascript MIME encoding. Our mission now would be to make checkusers.asp give the HTML file what it expects.

    Let's dive straight into checkusers.asp. First of all, I use the Response.ContentType property to set the response MIME type to application/x-javascript.

    
    <%
    Response.ContentType = "application/x-javascript"
    %>
    
    
    Now I have to begin building the JavaScript. The JavaScript in this file is basically going to contain an array of the user login names, and a function to take in the new user login as a parameter and check it with the existing login names array.
    
    <%
    ' Make the database connection
    Set DBConn = Server.CreateObject("ADODB.Connection")
    DBConn.Open "mydsn", "myuser", "mypass"
    
    ' Get all the user login names
    Set RSUsers = "select userlogin from LoginMaster"
    
    ' Create the JS Array
    Response.Write "var userArray = new Array();"
    
    ' Make an ASP counter
    Counter = 0
    
    ' If not EOF, then loop the recordset till EOF
    If Not RSUsers.EOF Then
    While Not RSUsers.EOF
    ' create the array elements
    Response.Write "userArray[" & Counter & "] = " & RSUsers(0)
    RSUsers.MoveNext
    Wend
    End If
    
     ' Write the JS Function that will do the actual validation
    Response.Write "function validateUser(newUserLogin)"
    Response.Write "{"
    Response.Write "userExists = false;"
    Response.Write "for(i=0;i<userArray.length();i++)"
    Response.Write "{"
    Response.Write "if(userArray[i] == newUserLogin) userExists = true;"
    Response.Write "}"
    Response.Write "return userExists;"
    Response.Write "}"
    
    %>
    
    
    So now when the SRC attribute calls this ASP file, it is fooled into believing that it is a JavaScript file because of the MIME type and because it contains valid JavaScript syntax. But this file is actually dynamically getting the user logins from the database and creating the array. It also encapsulates the function that checks the validity of the user.

    All we now need to do is go back to our HTML file and make sure that this function is called when the form is submitted. To enable this our FORM tag is modified as below:

    
    <FORM ACTION= "submitlogin.asp" METHOD=POST NAME= "loginform" onSubmit="return validateForm()">
    
    
    And we need to now add the JavaScript code for validateForm in the main HTML page.
    
    <SCRIPT LANGUAGE="JavaScript">
    function validateForm()
    {
    if(!validateUser(document.loginform.userlogin.value))
    {
    alert("This login name already exists in our database. Please choose a different login name.");
    document.loginform.userlogin.focus();
    return false;
    }
    }
    </SCRIPT>
    
    
    The code is almost self-explanatory. If validateUser method of the remote JavaScript file returns false for this user login, then it means that the user name already exists and hence the user is alerted that this login already exists in the database.

    Security Risk

    This method however brings the .js file into the Temporary Internet Files (or browser cache) and places the file there. Any user who opens the folder physically can still see the list of users in the site. Hence, the method is to be cautiously used where security is not a major issue.

    Pandurang Nayak is a web developer working in 3rdAgenda (http://www.3rdagenda.com), India. He is involved in development of Web based technologies like ASP, COM, ActiveX, DHTML, XML and WAP for the past two years.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    AspEncrypt
    Built around the Microsoft CryptoAPI, AspEncrypt helps you harness all major encryption and hashing algorithms such as DES, Triple-DES, RC2, RC4, RSA, MD5 and SHA1 in just a few lines of code. The component can be used in tandem with AspEmail to send encrypted and signed mail in the industry-standard S/MIME format, or with AspUpload to encrypt files as they are being uploaded. AspEncrypt can also be used to issue and manage X.509 digital certificates.
    [Top]
    AspPDF
    AspPDF is an ASP/ASP.NET component which enables generation and management of documents in PDF format. Features include advanced text formatting, font embedding, form fill-in, images, tables, content and page extraction, document stitching, encryption, digital signatures, and more.
    [Top]
    Other Articles
    Jun 6, 2002 - Client Side Validation Using the XMLHTTPRequest Object
    Jonathan Zufi shows how to use the XMLHTTP object within JavaScript or VBScript to validate form-field information without having to submit a page and wait for the result.
    [Read This Article]  [Top]
    Nov 6, 2001 - Writing Your Own Script File to Migrate a Database
    Learn how to write a script file using SQL Server's Bulk Copy Program for easy and speedy database migration.
    [Read This Article]  [Top]
    Sep 5, 2001 - Firing Events in a Shared Hosting Environment
    Firing events on a Web server is an easy task. However most of the easy solutions require you to have your own dedicated IIS or SQL Server on the Internet to play with, a privilege not shared by many. In this article, Matthew Muller shows you how to get the same functionality in a shared hosting environment.
    [Read This Article]  [Top]
    Jun 26, 2001 - Dynamically Changing Static Web Galleries
    Web galleries are an easy way to add interactivity and content to your Web site. However, how do you keep the Web galleries consistent with your site and how do you overcome the deficiencies of your Web gallery creation tool? John Sorensen explains a simple way to do both.
    [Read This Article]  [Top]
    Jun 8, 2001 - Implementing Dynamic Arrays of Objects
    Using classes in ASP 3.0 we can create dynamic arrays of objects. Donnell DeLeon Smith's article also shows how we can implement a class of dynamic arrays of objects several layers deep, if required.
    [Read This Article]  [Top]
    Mar 27, 2001 - Using ASP to Send a Wireless Text Message
    Even though SMS is now in high gear, developers remain slated with restrictive limits to carrier resources. Sending an SMS message via e-mail requires the acceptance of several hidden flaws. Joe Lauer shows how to avoid these complications by sending a wireless text-message through the use of ASP.
    [Read This Article]  [Top]
    Mar 1, 2001 - Server-Side Validations Using Regular Expressions
    Add punch to your validation routines by adding regular expressions. Further prepare yourself for the coming ASP.NET regular expression validation control. This article shows you how to use regular expressions and provides sample patterns for different user inputs.
    [Read This Article]  [Top]
    Sep 20, 2000 - How to Display File ACLs on Your Web Page without Active Directory
    Thought displaying file ACLs on a Web page in a browser was impossible without Active Directory installed? Think again. Through a patchwork of technologies, Larry Schwartz proves otherwise.
    [Read This Article]  [Top]
    Aug 3, 2000 - Recursive Functions
    A function that calls itself repeatedly, satisfying some condition is called a Recursive Function. Using recursion, we split a complex problem into its single simplest case. The recursive function only knows how to solve that simplest case. You'll see the difference between solving a problem iteratively and recursively later.
    [Read This Article]  [Top]
    Jul 27, 2000 - Effect of Using Multiple Scripting Languages in ASP
    Do you know what happens when you use multiple languages within your ASP page? Gopikrishna S throws light on how an ASP page behaves when multiple languages are used for server side scripting.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers