We recommend using Visual Studio 2017

Validation

 

Microsoft Corporation
October 2003

Applies to
    Microsoft® ASP.NET
    Microsoft ADO.NET
    Microsoft Visual Studio® .NET
    Java Server Pages

Summary: Learn how ASP.NET greatly simplifies form field validation when compared to JSP. (14 printed pages)

Contents

Introduction
Validation in JSP
Converting JSP to ASP.NET by using JLCA
Validation using ASP.NET

Introduction

In a Web application, validation is the process of determining whether text typed into a field or fields conforms to a certain template. If a Submit button is pressed and one or more of the fields is incorrect, the field is considered invalid and a message appears on the page to indicate this. If all fields are correct (valid), pressing the Submit button results in the form being processed and the user being sent to a new page.

The template to which a field must conform can be as simple as, "this field cannot be blank." But validation can also be much more complex. Validation can check a field to see whether it is identical to another field (as in "password" and "confirm password" fields), that they meet minimums or maximums for length or numerical value, or even that they conform to a complex regular expression. In this way, you can ensure that the information a user inputs into a Web form will be in exactly the format you want before the processing application begins its work.

Although the visible result of adding validation to forms in JSP and Microsoft® ASP.NET can be exactly the same, the process of doing so is very different. In this article, we will briefly demonstrate how validation is accomplished in a JSP page, and then convert that page to ASP.NET, showing how ASP.NET validation controls can greatly simplify the process of validating form data.

Validation in JSP

The CodeNotes Web site uses forms validation on several pages. In this article, we will use the New User Registration page to demonstrate validation in JSP and ASP.NET.

The registration page is a simple form with six fields, a checkbox, and a button. Its validation requirements are equally as simple:

  • None of the six fields may be left blank.
  • The Password and Re-enter Password fields must be identical.

If either of these rules is broken, a message is displayed near the top of the page listing the invalid fields and what they require. Note that validation only occurs when the Register button is clicked.

Listing 1 shows the code for the form as it appears in content_registerMain.jsp.

Listing 1. Form from Registration page of CodeNotes.com

<form name="registerForm"
   method="POST"
   action="<%=Links.linkToProcessRegister()%>"
   onSubmit="return validate()">

   <table>
      <tr>
         <td></td>
         <td class="bodycopyblack"><%=userMessage%></td>
      </tr>
      <tr>
         <td class="bodycopyblack">UserName/Email:</td>
         <td class="bodycopyblack">
            <input TYPE="TEXT" SIZE="30" 
               NAME="<%=Parameters.USERNAME%>" 
               value="<%=(username!=null?username:"")%>">
            <span class="asterisk" ID="usernameAsterisk">*</span>
         </td>
      </tr>
      <tr>
         <td class="bodycopyblack">Password:</td>
         <td class="bodycopyblack">
            <input TYPE="PASSWORD"
               NAME="<%=Parameters.PASSWORD%>">
            <span class="asterisk" ID="passwordAsterisk">*</span>
         </td>
      </tr>
      <tr>
         <td class="bodycopyblack">Re-enter Password:</td>
         <td class="bodycopyblack">
            <input TYPE="PASSWORD"
               NAME="<%=Parameters.CONFIRM_PASSWORD%>">
            <span class="asterisk" ID="confirmpasswordAsterisk">*</span>
         </td>
      </tr>
      <tr>
         <td class="bodycopyblack">FirstName:</td>
         <td class="bodycopyblack">
            <input TYPE="TEXT" SIZE="30"
               NAME="<%=Parameters.FIRSTNAME%>"
               value="<%=(firstName!=null?firstName:"")%>">
            <span class="asterisk" ID="firstnameAsterisk">*</span>
         </td>
      </tr>
      <tr>
         <td class="bodycopyblack">LastName:</td>
         <td>
            <input TYPE="TEXT" SIZE="30" 
               NAME="<%=Parameters.LASTNAME%>" 
               value="<%=(lastName!=null?lastName:"")%>">
            <span class="asterisk" ID="lastnameAsterisk">*</span>
         </td>
      </tr>
      <tr>
         <td class="bodycopyblack">DisplayName:</td>
         <td>
            <input TYPE="TEXT" SIZE="30"
               NAME="<%=Parameters.DISPLAYNAME%>"
               value="<%=(displayName!=null?displayName:"")%>">
            <span class="asterisk" ID="displaynameAsterisk">*</span>
         </td>
      </tr>
      <tr>
         <td colspan="2" class="bodycopyblack">
            <input type="checkbox" checked
               name="<%=Parameters.OPTIN%>"
               value="<%=Parameters.CHATNOTIFY%>">I would like
               to receive email about CodeNotes news and events
         </td>
      </tr>
      <tr>
         <td></td>
         <td class="bodycopyblack">
            <input TYPE="SUBMIT"
               VALUE="Register" class="button" NAME="Submit1">
         </td>
      </tr>
   </table>
</form>

As you can see in the <form> tag at the top of Listing 1, the onSubmit attribute calls a validate() method, which does the checking to see whether the form fields are valid. If validate() returns false, the submit action will be canceled. If validate() returns true, the form's action attribute will take over and the appropriate servlet will be executed to process the registration information and forward the user to the next page.

Fields

As you can see, each field in the form is placed in its own HTML table cell. After each <input> element, we placed a <span> element with a single character in it: an asterisk. This asterisk will be displayed only if the Register button has been clicked and the field was invalid. The functionality for hiding and displaying the asterisks is included in the validate() method, which we will discuss shortly.

The initial content of each field changes depending on whether the Register button has been clicked. The first time the page is visited, all fields are blank. When the Register button is clicked, the values currently in the fields are saved to variables (which are declared at the beginning of the content section of the JSP). Inside each field's value attribute, we check whether or not the appropriate variable has a value; if it does, we display that value so the user doesn't have to fill in that field again, and if it doesn't we simply display "" (a blank string). We perform this check mainly so that the application does not attempt to display a null string in a field and thus throw an exception.

Validation

As previously mentioned, the validate() JavaScript function is used to validate the content of each of the form fields. A separate if statement is required for each field. Listing 2, for example, shows the if statement that checks whether the Username/Email field is empty.

Listing 2. Validating a field in JavaScript

// This statement checks for a UserName/Email value.

if(trim(document.registerForm.<%=Parameters.USERNAME%>.value)=="") {
   showAsterisk(document.getElementById("usernameAsterisk"));
   requiredMessage=addToMessage(requiredMessage,"UserName/Email");
}

The above statement determines whether the UserName field is empty. If it is empty, it makes the asterisk next to that field visible and adds a message to requiredMessage (a hash of messages) indicating that there was a problem with this field.

Confirming that the Password field matches the Confirm Password field is done in a similar manner, as shown in Listing 3.

Listing 3 Performing a match validation in JavaScript

//This statement checks that Password = Confirmed_Password.
if(trim(document.registerForm.<%=Parameters.PASSWORD%>.value)
   != trim(document.registerForm.<%=Parameters.CONFIRM_PASSWORD%>.value))
{
   requiredMessage=addToMessage(requiredMessage,"The
   Confirmed Password and Password entry must be the same");
}

At the end of the validate() function, we check if there are any invalid fields and, if so, display an error message listing the fields that the user needs to fix. If there were error messages, the validate() function returns false indicating that the user needs to make changes to the form before submitting again. If there were no errors, validate() returns true, the form is submitted, and the user is forwarded to the next appropriate page. Listing 4 shows the code to accomplish all this.

Listing 4. Printing error messages

// This statement is used to display required value messages.
if(requiredMessage!="")
{
   message+="<H3>The following fields are
     required:</H3>"+requiredMessage+"</TD>";
}

document.getElementById("statusDIV").innerHTML=message;

// This statement is used for valid forms.
if(message=="")
{
   return true;
} 

else 
{
   return false;
}

The main advantage of JavaScript validation in JSP is that it is all done on the client side. This means that there is no need for a round-trip to the server in order to determine whether form data is valid.

However, in order to write the code for even the simplest JavaScript validation, you must have knowledge of multiple technologies such as the Document Object Model (DOM), Cascading Style Sheets (CSS), and HTML. In addition, the DOM for which you write your application may not be supported by all of your target browsers. ASP.NET overcomes these problems by allowing you to add validation using a simple GUI, automatically determining what client-side code is necessary, and then generating it on a client-by-client basis.

We'll see how easy it is to add validation controls using ASP.NET later. In the next section, however, we will look at how the Java Language Conversion Assistant (JLCA) converts the CodeNotes registration page into an ASP.NET project.

Converting JSP to ASP.NET by using JLCA

JLCA does an adequate job of converting the CodeNotes Web site registration page. That is, there are no major errors in the conversion process, nor is there a lot of work involved in fixing the minor errors and warnings that do arise. In addition, the final ASP.NET page looks virtually identical to the original JSP page, so there is no need to worry about appearance changes in your Web site due to conversion.

A Two-Step Process

One caveat to this relatively easy conversion task is that it must be done in two steps.

  1. Run the JLCA JSP to ASP.NET conversion wizard, as demonstrated in ViewState and JavaBeans. This will convert everything except for the required servlet classes. The reason for this is that in a functional, build version of the CodeNotes Web site, the servlet classes will already be compiled into .class files, and the conversion utility cannot decompile and convert them.
  2. In order to convert the servlets into C# code, you must obtain the original, un-compiled servlet classes (.java files) and use the JLCA Java to C# converter to transform them into .cs files. For our example, we will place the three newly created .cs files in a separate project within the same solution (the secondary project is called validationConvClasses in our sample solution, whereas the ASP.NET project itself is called validationConv).

Before either of these projects will compile, you will also need to use ProjectAdd Reference to add a reference to the System.Web namespace in the validationConvClasses project, and to add a reference to validationConvClasses from the validationConv project.

Unfortunately, even after you've run the conversion wizard on both sections of the application, it still will not compile right away. The next section discusses some of the minor changes you will need to make in order to complete the transformation into ASP.NET.

Completing the Process

The following are the sections of the registration page application you will need to change in order for it to work correctly in ASP.NET:

  1. The only error that will be reported when you convert the JSP project into ASP.NET is that the Web.Config customErrors mode property must be set to "On". To fix this problem, open the Web.config file and find the <customErrors> element. Change the value of its mode property from RemoteOnly to On. This allows custom error messages to be displayed to all users. Note that, as the comment text above the <customError> element says, RemoteOnly is often a more secure choice. The registration page application will run without this change being made, so you might want to consider leaving it if security is an issue.
  2. If you open content_registerMain.aspx, you'll notice that you are automatically taken to the HTML view of the page, and that you receive an error message if you try to switch to Design view. What this error message means is that ASP.NET does not support the following attribute formation:
    value="<%=(lastName!=null?lastName:"")%>"
    

    You'll recall that we used these condensed if/else statements in the JSP code so that the application would not try to output null strings (which would result in an exception). The reason ASP.NET does not allow this formation is because it contains a set of double-quotes nested within another set of double-quotes. However, because ASP.NET automatically outputs null strings as blank strings, there is no need for this if/else logic at all. After changing all occurrences of this attribute to something like the following, you will be allowed to switch to Design view.

    value="<%=(lastName)%>"
    
  3. You need to change the Import statement at the beginning of content_registerMain.aspx so that it references the classes in the validationConvClasses project. The original Import statement generated by JLCA is incorrect, as those classes (Links, Attributes, and Parameters) are no longer in the same location. Replace it with the following:
    <%@ Import Namespace="com.codenotes.web" %>
    

    Each of the .java files you converted to .cs still remains in the com.codenotes.web namespace, and this Import statement will allow your ASP.NET code to access them even though they are in a separate project.

  4. Links.java makes use of a class called URLEncoder several times in order to make sure special characters in page URLs are parsed correctly. Unfortunately, JLCA does not recognize this class and is not able to select a .NET class to take its place when it generates Links.cs. This equivalent functionality does exist in .NET in a class called System.Web.HttpUtility. However, you will need to make the changes manually in order to take advantage of this.

    In general, lines of code that look like this:

    sb.Append(Parameters.REFERRER).Append("=").Append(URLEncoder.encode(ref
      errerURL));
    

    should be modified as follows:

    sb.Append(Parameters.REFERRER).Append("=").Append(System.Web.HttpUtilit
      y.UrlEncode(referrerURL));
    

    As you can see, we are simply replacing the URLEncoder.encode() method with the System.Web.HttpUtility.UrlEncode() method. You will need to make three replacements in total.

  5. Although the JLCA maps many functions, a few slip through the cracks. The following method replacements should be made in content_registerMain.aspx:
    • All instances of Request.GetParameter() should be changed to Request.Params.Get().
    • All instances of Request.GetParameterSet() should be changed to Request.Params.GetValues().
    • All instances of Request.GetAttribute() should be changed to Request.Params.Get().

After making these changes, the validationConv project should compile and function exactly as the original JSP project did.

Validation using ASP.NET

We've seen how the JSP version of the CodeNotes Web site registration page works, and how it can be successfully converted to a functioning ASP.NET application using JLCA. However, in many cases it is more worthwhile to spend the time required to completely redesign a page in order to take advantage of the full scope of ASP.NET technologies, rather than convert from an existing JSP/Java application and then attempt to "tweak" it into a functional state. In this section, we'll design an ASP.NET application with exactly the same functionality as the JSP and converted JSP applications you've already seen. The best part is we'll do it without writing a single line of code.

Creating the ASP.NET Solution

Start a new C# ASP.NET solution in Microsoft Visual Studio® .NET. Call it whatever you like; we called ours validationNew. Open the Design view for WebForm1.aspx and drag labels and fields onto it so that it mimics the JSP version of the registration page.

Note that we linked most of our elements to the style sheet from the original CodeNotes Web site in order to have them look exactly the same. You can change the font sizes and styles manually if you want, but if you would like to implement the style sheet, you need to:

  1. Drag the style sheet file into the Solution Explorer to add it to the project.
  2. Open Format, Document Styles.
  3. Click Add Style Link, and then select the style sheet to add a reference to it.

You can now use the CssClass property of any element to change its appearance according to the classes defined in the style sheet file.

So, now we have a form that looks like the one from the JSP version. The next step is to add some ASP.NET validation controls so that it works like the JSP version.

Validation Controls

In order to duplicate the functionality of the JSP registration page, we're going to need to use three different ASP.NET controls: RequiredFieldValidators (six of them), a CompareValidator, and a ValidationSummary. For now, you simply need to know that:

  • RequiredFieldValidator is used to ensure that a field is not left blank.
  • CompareValidator is used to ensure that two fields are identical.
  • ValidationSummary is used to display a list of error messages produced by other validation controls on a page.

All three of these controls can be found in the Toolbox on the left side of Visual Studio .NET, at the bottom of the Web Forms section.

RequiredFieldValidators

We want to put a RequiredFieldValidator next to each field in the form. Drag six of them from the Toolbox. It will make your life easier if you match up the numbers of the RequiredFieldValidator instances with the numbers of the TextBox instances, but it is not necessary. Note that it doesn't matter how wide you make the RequiredFieldValidator objects as long as there is room for one character to be displayed.

We need to change a number of properties in order to make our page function similarly to the JSP registration page. These properties can all be modified by selecting a RequiredFieldValidator and editing the appropriate properties in the Properties box (usually in the bottom left corner of the Visual Studio .NET window). They are as follows:

  • Display should be set to Dynamic. This allows the application to dynamically add space to the page when a validation message is necessary. Other options include Static, which allocates space in the layout regardless of whether the message currently being displayed, or None, which indicates that the message will never be displayed.
  • ErrorMessage should be changed to match the appropriate error message as seen in the JSP registration page. This is the message that will appear in the list of errors we will create later. For example, the error message for the UserName/Email field should be (appropriately enough) "UserName/Email".
  • Text should be changed to the message that you actually want to display in-line when an error occurs. That is, this message will appear right where the RequiredFieldValidator object is. In this case, we want the message to be simply a * character.
  • ControlToValidate should be changed so that the RequiredFieldValidator knows which field it is supposed to be validating. This will be easy to determine if you matched up the numbers of your objects in the first place.

CompareValidator

A CompareValidator validates whether two fields in a form have the same contents. Adding a CompareValidator is much the same as adding a RequiredFieldValidator; you still need to edit the Display, ErrorMessage, and Text fields, as described in the previous section.

However, instead of simply selecting a ControlToValidate as before, you need to change the following:

  • ControlToCompare is the field to which another field will be compared. Confusingly enough, the ControlToCompare should be the one next to where you placed the control (the one that would have been referred to as the ControlToValidate in a RequiredFieldValidator). In this case, the ControlToCompare is the Password field.
  • ControlToValidate, in this case, is the field that must match up with the ControlToCompare field. In this case, the ControlToValidate is the Re-enter Password field.

Note that the best place to put this control (in terms of appearance) is directly on top of the RequiredFieldValidator next to the Password field. This makes sure that a * character will appear in the same place regardless of what error actually occurs (missing field, or mismatched password and password confirm fields).

Before continuing, you probably also want to make sure that the TextMode property of each of your Password and Confirm Password fields (the fields, not the validation controls) is set to "Password," so that text entered in these fields is not visible when the application is run.

ValidationSummary

Finally, we're going to add a ValidationSummary object to our ASP.NET registration page. This object keeps track of which validation controls have detected errors in form data, and displays their ErrorMessage fields in a single list. Since this is how it is done in the JSP registration page, we will imitate it in ASP.NET.

Drag a ValidationSummary object onto the page, and change its HeaderText property to something like "The following fields are required:" We also changed its CssClass property to "H3" so it looks more like the JSP version.

Unfortunately, there is one problem with the ValidationSummary object that will prevent us from exactly imitating the JSP registration page: it is not possible to set it to display dynamically so that space is allocated for it only when it is actually present. This means that you can't simply drop the ValidationSummary on top of your fields in the correct position and assume that they'll move out of the way when required; they won't. We're going to solve the problem the easy way, and simply place the ValidationSummary below the fields instead of above it. It won't look exactly the same as the JSP, but it is close enough. In order to have space dynamically allocated for this object, you would need to manually edit the HTML, which we promised we wouldn't do. If you'd like to, you can find out how it's done by looking at content_registerMain.jsp.

Final Notes

You can now run your ASP.NET application and see that it is functionally identical to the original JSP. The only difference is that the Register button doesn't do anything yet, other than cause the form to validate itself. You will need to edit the codebehind for the Register button in order to have it redirect the user to the correct place (and do something with the valid form data).

Show: