19.2. Forcing the User to Enter Something
Most forms have required fields that the user must not leave blank. For example, a login page can't get far without some sort of identifier, such as a username. The RequiredFieldValidator control insists that the user enter something in the field, even if it's gibberish.
The validator is hard to fool; spaces don't count as an entry. What's more, the control recognizes default text and treats that particular something as nothing. Follow these steps to add and configure the RequiredFieldValidator control:
From the Toolbox, add a TextBox control to an ASP.NET page and set its Text property to Enter Your User ID.
Enter Your User ID is an instruction to the user and can't be counted as a username.
Add a Button control to the page.
Add a RequiredFieldValidator control to the page and set the following properties to their corresponding values:
| Property | Value |
|---|---|
| ControlToValidate | TextBox1 (or whatever yours is called) |
| Display | Dynamic |
| InitialValue | Enter Your User ID |
| SetFocusOnError | True |
| Text | * Type something else! |
| ToolTip | Enter your user name |
Open the page in the browser and click the Submit button. Even though text is in the text box, the InitialValue property of the RequiredFieldValidator signals that the user must enter something other than the default text.
Setting the Display to Dynamic avoids a postback by using JavaScript to display the error message. The SetFocusOnError property enhances usability by putting the cursor into the TextBox control where the error ...