2.1. Requiring that Data be Entered in a Field
Problem
You need to ensure that a user has entered data in a text box, such as a first or last name on a registration form.
Solution
Add a RequiredFieldValidator control to the
.aspx file,
and
use the event handler of the control that completes the
user’s entry for the page to verify that validation
was successful.
In the .aspx file:
Add a
RequiredFieldValidatorcontrol for each text box in which data must be entered.Add Save and Cancel (or equivalently named) buttons.
Set the Save button’s
CausesValidationattribute toTrueto have validation performed when the button is clicked (set it toFalsefor the Cancel button).
In the code-behind class, use the .NET language of your choice to add
code to the event handler for the Save button’s
click event that checks the Page.IsValid property
and verifies that all validation was successful.
Figure 2-1 shows a typical user input form with
fields for First Name and Last Name and several other types of
information. Figure 2-2 shows the same form with
validation error messages that appear when the user fails to complete
the First Name and Last Name fields. Example 2-1
shows the .aspx file that implements the form,
and Example 2-2 and Example 2-3 show the VB and C# code-behind files needed to
complete the application.

Figure 2-1. Form with required field validation output—normal
Figure 2-2. Form with required ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access