The Web Forms framework includes a set of validation server controls that provide an easy-to-use yet powerful way to check input forms for errors, and, if necessary, display messages to the user.
Validation controls are added to an ASP.NET page like other server controls.
There are controls for specific types of validation, such as range checking or pattern matching, plus a RequiredFieldValidator to ensure that a user does not skip an entry field.
The following example demonstrates how to use an <asp:requiredfieldvalidator
> control on a Web Forms page to validate the contents of a TextBox control.
<p>Enter your name: <asp:textbox id="userName" runat="server" />
<asp:button text="Enter" onClick="greetUser" runat="server" />
<asp:requiredfieldvalidator
controltovalidate="userName"
display="dynamic"
errormessage="Please enter a name. Sender's name cannot be blank."
forecolor="navy" font-bold
runat="server" />
In the example, a method named greetUser has been assigned to handle the onClick event of the <asp:button
> control used to submit the form.
<asp:button text="Enter" onClick="greetUser" runat="server" />
The message is displayed only if the page passes the conditional check, as shown below.
<script language="C#" runat="server">
void greetUser ( Object Src, EventArgs E ) {
if ( Page.IsValid ) {
message.InnerHtml = "Hello, " + userName.Text +
"<br>Welcome to Web Forms Validation";
}
}
</script>
In a page with validation controls, the Page.IsValid property is set after all validation controls have been processed.
It returns a value indicating whether page validation succeeded. If any of the controls reveals that a validation check has failed, the entire page is set to invalid.
The condition we set-up ( "Is the page valid?" ) then evaluates to false, and no message is displayed.
If a validation control is in error, the specified errormessage displays in the validation control set somewhere on the page.
For more information, see Web Forms Validation.