Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Building Microsoft ASP.NET Applications for Mobile Devices, Second Edition [Electronic resources] - نسخه متنی

Andy Wigley; Peter Roxburgh

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
توضیحات
افزودن یادداشت جدید






Validation Controls

Form validation is an essential part of any mobile Web application. You perform validation for a number of reasons—among them, ensuring that your code meets these conditions:



Form fields are completed.



Values correspond to a particular format, such as an e-mail address.



Two fields contain the same value—for example, when a user enters his or her password and confirms it.



Traditionally, performing these tasks has required server-side programming, which often requires extensive use of complex regular expressions. If you've worked with regular expressions before, you know how troublesome programming them can be.

ASP.NET offers a new, flexible method of performing form validation: using server validation controls. These controls allow you to perform complex validation tasks by simply inserting server validation control tags in your Web Forms page. The controls enable actions that range from straightforward checking of field completion to comparing user input against regular expressions. Figure 5-5 shows the class hierarchy of the mobile validation controls.


Figure 5-5: Class hierarchy of the server validation controls

You use the RequiredFieldValidator control to ensure that a user cannot exit a Form until they have entered a value in some other control, such as a TextBox. The CompareValidator control is used to compare the values in two other controls on the page, for example TextBox1.Text == TextBox2.Text, and allow the user to leave the Form only if the comparison statement evaluates True. The RangeValidator control verifies that the user has entered a value into an entry field that lies between limit values that you specify. The RegularExpressionValidator control allows you to check that the value of a field conforms to a given character pattern, for example that it is a valid e-mail address, a ZIP code, or a social security number. The CustomValidator control allows you to write your own validation method; during page validation, your custom validation method is used alongside all the standard validation controls. The ValidationSummary control is used to amalgamate the output from all the validation controls on a Web Forms page so that the error messages can be presented together, rather then singly.

The mobile validation controls provide functionality similar to a set of ASP.NET controls intended for validating desktop client input. However, unlike the ASP.NET controls, which might add Microsoft JScript to the Web page sent to desktop browsers to perform client-side validation, the mobile validation controls never execute on the client. Instead, they execute on the server, after the client posts the form data. If the data is invalid, you can program against this result or allow ASP.NET to return the page to the user for correction.





Note

Server validation controls used within mobile Web applications always execute on the server. However, in standard ASP.NET, you can execute some of the validation controls on the client by using client-side script. You can't do this with mobile applications, even if you know that a client supports client-side script.



Common Behavior of the Validation Controls


All the Validation controls, except ValidationSummary, inherit from System.Web.UI.MobileControls.BaseValidator. The most important property is IsValid which is true if the control's validation criteria have been satisfied, or false if the user's input has failed validation. The System.Web.UI.Page class (parent class of the MobilePage class) also has the IsValid property, which is the logical AND of the IsValid property of all validation controls on the page.

The typical way of using the Validation controls, is to test the IsValid property of the Page before allowing navigation away from the page being validated. To get a reference to the parent System.Web.UI.Page instance, use the MobilePage.Page property. The following example is a Command control Click event handler in a class derived from MobilePage:

        protected void Command1_Click(object sender, System.EventArgs e)
{
// Move onto second Form only if input on first page has
// passed validation by all the validation controls on the page
if (Page.IsValid)
{
ActiveForm = Form2;
}
}

With logic such as this, the Form with the validation controls on it now redisplays, but this time with error messages displayed by each of the validation controls that have detected a validation error.

Validation controls display error messages in two ways; either at the position where you placed the validation control on the Form, or in the display of a ValidationSummary control. You define the error message that displays at the control position using the Text property. You define the error message that goes into the ValidationSummary control display using the ErrorMessage property. If you have not set the Text property, then ErrorMessage is used for the control error message as well. You can turn off the display of the message at the position of the control, so that the message only appears in the ValidationSummary control, by setting the Display property to None. Error messages display next to the validation controls if the Display property is set to Static or Dynamic.





Note

Display.Static and Display.Dynamic behave the same way in the ASP.NET mobile controls. This enumeration is inherited from the ASP.NET versions targeted at desktop browsers, and these values cause different behavior depending on whether the client browser supports client-side scripting or not.






Note

With the mobile controls, no client-side validation takes place, so the behavior of Display.Static and Display.Dynamic is the same: an error message displays when a validation error occurs.


By default, the validation controls use StyleReference="error" to format the error message, which on an HTML browser displays the associated error message in red. You can use the style properties inherited from MobileControl to alter this behavior.

If the Visible property of a validation control is False, it doesn't just mean that the error message isn't displayed—it means that the control doesn't perform validation.

The use of the common properties inherited from the BaseValidator class is summarized in Table 5-5.



























Table 5-5: Common Properties of the Validation Controls


Property


Type


Description


ControlTo-Validate


String


The ID of the control to validate.


Display


System.Web.UI.WebControls.ValidatorDisplay enumeration: None|Static|Dynamic


The display behavior of the control. If this property is set to Dynamic or Static, an error message is displayed when a validation error occurs. If Display is set to None, error messages won't be displayed by the RequiredFieldvalidator control, but they will still appear in the output from the ValidationSummary control (discussed later in this chapter).


ErrorMessage


String


The message displayed in the output of the ValidationSummary control. If the Text property is blank and Display isn't set to None, this value is displayed next to the control being validated in the event of an error.


IsValid


True|False


Indicates whether the data is valid.


Text


String


The message displayed in the event of an error. If this property has no value, the control displays the ErrorMessage value instead. The Text property isn't included in the ValidationSummary control's output; use ErrorMessage for this purpose.



RequiredFieldValidator Control


The RequiredFieldValidator control, the simplest of the validation controls, is the one you'll use most frequently. This control simply checks whether a user has entered a value for an input control.

Syntax


You code the RequiredFieldValidator control in server control syntax using the properties and values shown in the following listing. See Table 5-6 for descriptions of the purpose of the properties listed here.

<mobile:RequiredFieldValidator
runat="server"
id="id"
BreakAfter="{True|False}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
ForeColor="foregroundColor"
BackColor="backgroundColor"
Alignment="{NotSet|Left|Center|Right}"
StyleReference="styleReference"
Visible="{True|False}"
Wrapping="{NotSet|Wrap|NoWrap}"
ControlToValidate="IdOfTargetControl"
Display="{None|Static|Dynamic}"
ErrorMessage="ErrorTextForSummary"
InitialValue="initialValueInTheControl"
Text="ErrorText">
innerText
</mobile:RequiredFieldValidator>






























Table 5-6: Significant Properties of the RequiredFieldValidator Control


Property


Type


Description


ControlTo-Validate


String


The ID of the control to validate. This property inherits from the BaseValidator class. See Table 5-5 for details.


Display


ValidatorDisplay.None|Static|Dynamic


This property inherits from the BaseValidator class. See Table 5-5 for details.


ErrorMessage


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


InitialValue


String


The initial value of the control. The RequiredFieldValidator control compares the value submitted to the server with this value. If the two values are the same, the control assumes that the required field is incomplete.


IsValid


True|False


This property inherits from the BaseValidator class. See Table 5-5 for details.


Text


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


Properties


Table 4-1 for details of those properties that are inherited from MobileControl.) The Type column describes the type of the property when setting or getting the property in code. Refer to the preceding "Syntax" section for valid values when setting the property in server control syntax.

Using the RequiredFieldValidator Control


Listings 5-8 and 5-9 prompt the user to enter his or her name into a form. When the form data posts to the server, the RequiredFieldValidator control validates the userName field.

Listing 5-8: Source file RequiredExample.aspx






<%@ Page Inherits="MSPress.MobWeb.ReqEx.RequiredExample"
CodeBehind="RequiredExample.aspx.cs"
Language="C#"%>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label id="Label1" runat="server">
Your name:
</mobile:Label>
<mobile:TextBox id="userName" runat="server"/>
<mobile:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server"
Display="Dynamic"
ErrorMessage="Your name is required! "
ControlToValidate="userName"/>
<mobile:Command id="Command1" OnClick="Command1_Click" runat="server">
Submit
</mobile:Command>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:Label id="Label2" runat="server">
Input validated OK.
</mobile:Label>
</mobile:Form>












Listing 5-9: Code-behind file RequiredExample.aspx.cs






using System;
namespace MSPress.MobWeb.ReqEx
{
public class RequiredExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.TextBox userName;
protected System.Web.UI.MobileControls.RequiredFieldValidator
RequiredFieldValidator1;
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.Form Form1;
protected System.Web.UI.MobileControls.Label Label2;
protected System.Web.UI.MobileControls.Form Form2;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Command1.Click +=
new System.EventHandler(this. Command1_Click);
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form2;
}
}
}
}











When the user accesses the Web Forms page and doesn't enter a value in the name field, the application marks the page as invalid. Figure 5-6 shows the message Pocket Internet Explorer displays when this happens.


Figure 5-6: Input page and returned page with missing field


CompareValidator Control


The CompareValidator control allows you to compare the values of two input controls.

Syntax


You code the CompareValidator control in server control syntax using the properties and values shown in the following listing. See Table 5-7 for descriptions of the properties listed here.

<mobile:CompareValidator
runat="server"
id="id"
BreakAfter="{True|False}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
ForeColor="foregroundColor"
BackColor="backgroundColor"
Alignment="{NotSet|Left|Center|Right}"
StyleReference="styleReference"
Visible="{True|False}"
Wrapping="{NotSet|Wrap|NoWrap}"
ControlToCompare="IdOfControl"
ControlToValidate="IdOfTargetControl"
Display="{None|Static|Dynamic}"
ErrorMessage="ErrorTextForSummary"
Operator="{DataTypeCheck|Equal|GreaterThan|
GreaterThanEqual|LessThan|
LessThanEqual|NotEqual}"
Text="errorText"
Type="{Currency|DateTime|Double|Integer|String}"
ValueToCompare="Value">
innerText
</mobile:CompareValidator>

Properties


Table 4-1 for details of those properties that are inherited from MobileControl.) The Type column describes the type of the property when setting or getting the property in code. Refer to the preceding "Syntax" section for valid values when setting the property in server control syntax.







































Table 5-7: Significant Properties of the CompareValidator Control


Property


Type


Description


ControlToValidate


String


The ID of the control to validate. This property inherits from the BaseValidator class. See Table 5-5 for details.


ControlToCompare


String


The ID of the control to compare. Set this property if you want to compare the Text property of the ControlToValidate control to the Text property of another control. If you want to do the comparison against a fixed value rather than the value of another control, use ValueToCompare.


Display


ValidatorDisplay.None|Static|Dynamic


This property inherits from the BaseValidator class. See Table 5-5 for details.


ErrorMessage


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


IsValid


True|False


This property inherits from the BaseValidator class. See Table 5-5 for details.


Operator


System.Web.UI.Web-Controls.Validation-CompareOperator enumeration: DataTypeCheck|Equal|GreaterThan|GreaterThan-Equal|LessThan|LessThan-Equal|NotEqual


The operator that compares the control values. Use DataTypeCheck to ensure that the data types for the ControlToValidate and ControlToCompare properties are both of the type set in the Type attribute. The other comparison operators function as though ControlToValidate is on the left side of the operator, and ControlToCompare is on the right.


Text


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


Type


System.Web.UI.Web-Controls.Validation-DataType enumeration: String|Integer|Double|Date|Currency


Sets or gets the data type of the two values being compared. The values are implicitly converted to the specified data type before the comparison is made. If the types can't be converted, the validation fails.


ValueTo-Compare


String


Set this property if you want to compare the Text property of the ControlToValidate control to a constant value rather than the Text property of another control (use ControlToCompare instead of ValueToCompare for that). If you set both the ValueToCompare and ControlToCompare properties, ControlToCompare takes precedence.


Using the CompareValidator Control


Listings 5-10 and 5-11 prompt the user to enter his or her password and then reenter it in a second TextBox control. When the form data posts to the server, the CompareValidator control validates the fields to check that they have the same value.

Listing 5-10: Source file CompareExample.aspx






<%@ Page Inherits="MSPress.MobWeb.CmpEx.CompareExample"
CodeBehind="CompareExample.aspx.cs"
Language="C#"%>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label runat="server">
Your Password
</mobile:Label>
<mobile:TextBox id="password1" runat="server" password="true"/>
<mobile:Label runat="server">
Retype password
</mobile:Label>
<mobile:TextBox id="password2" runat="server" password="true"/>
<mobile:CompareValidator id="CompareValidator1"
Type="String"
Operator="Equal"
runat="server"
ErrorMessage="Passwords do not match!"
ControlToCompare="password1"
ControlToValidate="password2"/>
<mobile:Command id="Command1"
OnClick="Command1_Click" runat="server">
Submit
</mobile:Command>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:Label runat="server">
Passwords match!
</mobile:Label>
</mobile:Form>












Listing 5-11: Code-behind file CompareExample.aspx.cs






using System;
namespace MSPress.MobWeb.CmpEx
{
public class CompareExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.TextBox password1;
protected System.Web.UI.MobileControls.Label Label2;
protected System.Web.UI.MobileControls.TextBox password2;
protected System.Web.UI.MobileControls.CompareValidator
CompareValidator1;
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.Form Form1;
protected System.Web.UI.MobileControls.Label Label3;
protected System.Web.UI.MobileControls.Form Form2;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Command1.Click +=
new System.EventHandler(this. Command1_Click);
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form2;
}
}
}
}











Figure 5-7 shows the password input page and the page returned when the two passwords the user enters don't match.


Figure 5-7: Password input page and returned page, which contains the error message


RangeValidator Control


The RangeValidator control allows you to test whether a value falls within a specified range.

Syntax


You code the RangeValidator control in server control syntax using the properties and values shown in the following listing. See Table 5-8 for descriptions of the properties listed here.

<mobile:RangeValidator
runat="server"
id="id"
BreakAfter="{True|False}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
ForeColor="foregroundColor"
BackColor="backgroundColor"
Alignment="{NotSet|Left|Center|Right}"
StyleReference="styleReference"
Visible="{True|False}"
Wrapping="{NotSet|Wrap|NoWrap}"
ControlToValidate="IdOfTargetControl"
Display="{None|Static|Dynamic}"
ErrorMessage="ErrorTextForSummary"
MinimumValue="minValue"
MaximumValue="maxValue"
Text="errorText"
Type="{Currency|DateTime|Double|Integer|String}">
innerText
</mobile:RangeValidator>




































Table 5-8: Significant Properties of the RangeValidator Control


Property


Type


Description


ControlToValidate


String


The ID of the control to validate. This property inherits from the BaseValidator class. See Table 5-5 for details.


Display


ValidatorDisplay.None|Static|Dynamic


This property inherits from the BaseValidator class. See Table 5-5 for details.


ErrorMessage


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


IsValid


True|False


This property inherits from the BaseValidator class. See Table 5-5 for details.


MinimumValue


String


The minimum value of the ControlToValidate that will successfully validate.


MaximumValue


String


The maximum value of the ControlToValidate property that will successfully validate. Both MinimumValue and MaximumValue are required properties.


Type


System.Web.UI.WebControls.ValidationDataType enumeration: String|Integer|Double|Date|Currency


Sets or gets the data type of the value being validated. The Text property of the control being validated and the values of the MinimumValue and MaximumValue properties are implicitly converted to the specified data type before the comparison is made. If they can't be converted, the validation fails.


Text


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


Properties


Table 4-1 for details of those properties that are inherited from MobileControl.) The Type column describes the type of the property when setting or getting the property in code. Refer to the preceding "Syntax" section for valid values when setting the property in server control syntax.

When the RangeValidator control compares two strings, it does so by alphabetic precedence. For example, if the MinimumValue property has the value ABRA and the MaximumValue is CADABRA and the control to be validated contains the single character string B, the validation succeeds because B would appear after ABRA in an alphabetical sorted list, but before CADABRA. Similarly, ABS validates successfully against the range of ABRA to CADABRA. However, AB fails because it would come before ABRA in an alphabetical sorted list.

You should bear in mind two caveats when working with fields and user input:



If the user submits a blank field, the RangeValidator control will deem that field valid. To ensure that the user enters a value for a field and that the value is of a given data type, use the RequiredFieldValidator control as well as the RangeValidator control.



If the user submits a floating-point number when the syntax calls for an integer, the RangeValidator control will deem that input invalid. If you want to allow the user to enter a floating-point number, specify the value Double for the Type controls property.



Using the RangeValidator Control


Listings 5-12 and 5-13 prompt the user to enter his or her birthday in a TextBox control in a form. Part of the initialization of the RangeValidator control happens in the Page_Load method, where the MaximumValue is set to 21 years before today's date. When the form data posts to the server, the RangeValidator control checks whether the value indicates that the user is at least 21 years old.

Listing 5-12: Source file RangeExample.aspx






<%@ Page Inherits="MSPress.MobWeb.RgeEx.RangeExample"
CodeBehind="RangeExample.aspx.cs"
Language="C#" AutoEventWireup="False" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label runat="server">
Date of birth:
</mobile:Label>
<mobile:TextBox id="dob" runat="server"></mobile:TextBox>
<mobile:RangeValidator id="RangeValidator1" runat="server"
MinimumValue="01/01/1900"
ControlToValidate="dob"
ErrorMessage="Sorry, you are not 21.">
</mobile:RangeValidator>
<mobile:Command id="Command1" runat="server" text="Submit">
</mobile:Command>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:Label id="Label2" runat="server">
Welcome, you are over 21.
</mobile:Label>
</mobile:Form>












Listing 5-13: Code-behind file RangeExample.aspx.cs






using System;
namespace MSPress.MobWeb.RgeEx
{
public class RangeExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.RangeValidator
RangeValidator1;
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.TextBox dob;
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.Form Form1;
protected System.Web.UI.MobileControls.Label Label2;
protected System.Web.UI.MobileControls.Form Form2;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
this.Command1.Click +=
new System.EventHandler(this. Command1_Click);
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form2;
}
}
private void Page_Load(object sender, System.EventArgs e)
{
DateTime now = DateTime.Now;
DateTime dt21yearsago =
new DateTime(now.Year - 21, now.Month, now.Day, 0, 0, 0);
RangeValidator1.MaximumValue =
dt21yearsago.ToShortDateString();
RangeValidator1.Type =
System.Web.UI.WebControls.ValidationDataType.Date;
}
}
}











Figure 5-8 shows the birthday input field and the message that appears if the user isn't 21.


Figure 5-8: Output from RangeValidator example


RegularExpressionValidator Control


The RegularExpressionValidator control allows you to check that the value of a field conforms to a given character pattern. For example, you can use this control to validate an e-mail address, a ZIP code, or a social security number. This control is more complex than the validation controls we've discussed so far. It will help if you're familiar with regular expression syntax; however, working with this validation control is still significantly simpler than programming with traditional regular expressions.

Syntax


You code the RegularExpressionValidator control in server control syntax using the properties and values shown in the following listing. See Table 5-9 for descriptions of the properties listed here.

<mobile:RegularExpresssionValidator
runat="server"
id="id"
BreakAfter="{True|False}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
ForeColor="foregroundColor"
BackColor="backgroundColor"
Alignment="{NotSet|Left|Center|Right}"
StyleReference="styleReference"
Visible="{True|False}"
Wrapping="{NotSet|Wrap|NoWrap}"
ControlToValidate="IdOfTargetControl"
Display="{None|Static|Dynamic}"
ErrorMessage="ErrorTextForSummary"
Text="ErrorText">
ValidationExpression="regexp" >
innerText
</mobile:RegularExpressionValidator>

Properties


Table 4-1 for details of those properties that are inherited from MobileControl.) The Type column describes the type of the property when setting or getting the property in code. Refer to the preceding "Syntax" section for valid values when setting the property in server control syntax.






























Table 5-9: Significant Properties of the RegularExpressionValidator Control


Property


Type


Description


ControlToValidate


String


The ID of the control to validate. This property inherits from the BaseValidator class. See Table 5-5 for details.


Display


ValidatorDisplay.None|Static|Dynamic


This property inherits from the BaseValidator class. See Table 5-5 for details.


ErrorMessage


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


IsValid


True|False


This property inherits from the BaseValidator class. See Table 5-5 for details.


Text


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


ValidationExpression


String


The regular expression against which to validate the ControlToValidate property.









Using Regular Expressions in Microsoft Visual Studio .NET


Constructing regular expressions can be daunting. However, Visual Studio .NET helps by providing a selection of prewritten, commonly used expressions. You can find these expressions in the Regular Expression Editor, which you can access by dragging a RegularExpressionValidator control onto a Form, then pressing the … button next to the ValidationExpression property shown in the Properties window. This displays the Regular Expression Editor window where you can select a prebuilt expression or enter a custom regular expression.











Using the RegularExpressionValidator Control


Regular expression syntax is a large topic that's beyond the scope of this book. However, Listings 5-14 and 5-15 demonstrate a common use of regular expression validation: confirming a ZIP code. The regular expression for this is "\d{5}(-\d{4})?" which means that the entered text must consist of five digits, followed by an optional portion of a dash followed by four digits. For detailed information about regular expression syntax, refer to the System.Text.RegularExpressions.Regex class in the Visual Studio .NET documentation.

Listing 5-14: Source file RegularExample.aspx






<%@ Page Inherits="MSPress.MobWeb.RegEx.RegularExample"
CodeBehind="RegularExample.aspx.cs" Language="c#"%>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label runat="server">
ZIP Code
</mobile:Label>
<mobile:TextBox id="zip" runat="server"/>
<mobile:Command id="Command1" runat="server" OnClick="Command1_Click">
Submit
</mobile:Command>
<mobile:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Invalid ZIP Code"
ControlToValidate="zip" ValidationExpression="\d{5}(-\d{4})?"/>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:Label runat="server">
Valid ZIP Code
</mobile:Label>
</mobile:Form>












Listing 5-15: Code-behind file RegularExample.aspx.cs






using System;
namespace MSPress.MobWeb.RegEx
{
public class RegularExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.TextBox zip;
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.RegularExpressionValidator
RegularExpressionValidator1;
protected System.Web.UI.MobileControls.Form Form1;
protected System.Web.UI.MobileControls.Label Label2;
protected System.Web.UI.MobileControls.Form Form2;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Command1.Click +=
new System.EventHandler(this. Command1_Click);
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form2;
}
}
}
}











With a minor adjustment, you can also use Listings 5-12 and 5-13 to validate an e-mail address. The only change you need to make to the .aspx file just shown is to give the ValidationExpression attribute of the RegularExpressionValidator control a different value. Change the value of the ValidationExpression attribute to the following:

\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

This expression forces the input to be a grouping of any number of word characters (\w+, which means anything from the ranges A–Z, a–z, or 0–9) separated by -, +, or . characters ([-+.]) followed by more word characters, with that group repeated zero or more times (the (…)* construct). That part is followed by an @ character, after which there can be any number of words separated by – or ., but there must be at least a dot followed by a word.





Note

Like all other mobile controls, the RegularExpressionValidation control executes on the server rather than on the client. In contrast, the standard ASP.NET RegularExpressionValidation control used with desktop clients does support client-side execution.



CustomValidator Control


The CustomValidator control differs from the other validation controls because it doesn't directly provide validation functionality. Instead, this control allows you to create your own validation method, which it then references. In many ways, this control acts as a wrapper class, offering a way of implementing a validation method that operates in a consistent manner to the other validation controls.

Syntax


You use the ControlToValidate, Display, ErrorMessage, and Text properties in exactly the same way you do with all the other validation controls. An event handler for the ServerValidate event is required for this control. You can wire it up in server control syntax, or in code in the code-behind module. The following listing shows the server control syntax for the CustomValidator control.

<mobile:CustomValidator
runat="server"
id="id"
BreakAfter="{True|False}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
ForeColor="foregroundColor"
BackColor="backgroundColor"
Alignment="{NotSet|Left|Center|Right}"
StyleReference="styleReference"
Text="ErrorText"
Visible="{True|False}"
Wrapping="{NotSet|Wrap|NoWrap}"
ControlToValidate="IdOfTargetControl"
Display="{None|Static|Dynamic}"
ErrorMessage="ErrorTextForSummary"
OnServerValidate="EventHandler"
Text="ErrorText">
innerText
</mobile:CustomValidator>

Properties


Table 4-1 for details of those properties that are inherited from MobileControl.) The Type column describes the type of the property when setting or getting the property in code. Refer to the preceding "Syntax" section for valid values when you're setting the property in server control syntax.






























Table 5-10: Significant Properties and Events of the CustomValidator Control


Property or Event


Type


Description


ControlToValidate


String


The ID of the control to validate. This property inherits from the BaseValidator class. See Table 5-5 for details.


Display


ValidatorDisplay.None|Static|Dynamic


This property inherits from the BaseValidator class. See Table 5-5 for details.


ErrorMessage


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


IsValid


True|False


This property inherits from the BaseValidator class. See Table 5-5 for details.


ServerValidate (Event)


Event handler method


The control raises this event when the page is validated on the server. The event handler receives a ServerValidateEventArgs parameter. The event handler must set the IsValid property of the ServerValidateEventArgs object to true if validation is successful.


Text


String


This property inherits from the BaseValidator class. See Table 5-5 for details.


The CustomValidator control has one event, ServerValidate. The control raises the event when the page passes to the server for validation. Set the IsValid property of the ServerValidateEventArgs to indicate validation success or failure, as in this example:

void ServerValidate (Object source, ServerValidateEventArgs args )
{
args.IsValid=false;
// Code to validate the user's input


if (validationIsSuccessful)
args.IsValid=true;
}


Using the CustomValidator Control


Listings 5-16 and 5-17 prompt the user to enter an integer in a form. When the form data posts to the server, the CustomValidator control validates the field to verify whether the value is a factor of 4.

Listing 5-16: Source file CustomExample.aspx






<%@ Page Inherits="MSPress.MobWeb.CusEx.CustomExample"
CodeBehind="CustomExample.aspx.cs"
Language="C#"%>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label runat="server">
Enter an integer
</mobile:Label>
<mobile:TextBox id="number" runat="server"/>
<mobile:CustomValidator id="CustomValidator1"
runat="server"
ErrorMessage="Not a factor of four"
ControlToValidate="number"
OnServerValidate="ServerValidate"/>
<mobile:Command id="Command1"
OnClick="Command1_Click" runat="server">
Submit
</mobile:Command>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:Label runat="server">
A factor of four.
</mobile:Label>
</mobile:Form>












Listing 5-17: Code-behind file CustomExample.aspx.cs






using System;
using System.Web.UI.WebControls;
namespace MSPress.MobWeb.CusEx
{
public class CustomExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Form Form2;
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.CustomValidator
CustomValidator1;
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.Form Form1;
protected System.Web.UI.MobileControls.Label Label2;
protected System.Web.UI.MobileControls.TextBox number;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Command1.Click +=
new System.EventHandler(this.Command1_Click);
this.CustomValidator1.ServerValidate +=
new ServerValidateEventHandler(this.ServerValidate );
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form2;
}
}
protected void ServerValidate (
object source,
ServerValidateEventArgs args)
{
args.IsValid=false;
try
{
int x = Int32.Parse(number.Text);
if (x % 4==0)
{
args.IsValid=true;
}
}
catch(FormatException e)
{
// Exception may be caused by
// non-integer input on HTML clients
}
}
}
}












ValidationSummary Control


The ValidationSummary control returns a summary of all the output from the validation controls a Web Forms page contains. This control's output can be very useful in a mobile application because it enables you to present error messages in a single block of text. You can therefore significantly improve the usability of an application on a device with limited display characteristics.

Syntax


You can place this control in the same Form control that contains the validation controls. After control has returned to the server and validation has taken place, the ValidationSummary control displays a list containing the ErrorMessage property value of each validation control for which IsValid is False.

Alternatively, place this control in a different Form control from the one that contains the validation controls. The Click event handler of the Command control that triggers validation should test the Page.IsValid property and set the ActiveForm property to the Form control containing the ValidationSummary control if Page.IsValid == False. In this case, you should set a value for the BackLabel property, typically something like Retry. When BackLabel has a value, the ValidationSummary control renders a link to return to the Form being validated, using the value of BackLabel as the link text, as shown in the code below, in Listings 5-18 and 5-19. The following listing shows the server control syntax for the ValidationSummary control.

<mobile:ValidationSummary
runat="server"
id="id"
BreakAfter="{True|False}"
Font-Name="fontName"
Font-Size="{NotSet|Normal|Small|Large}"
Font-Bold="{NotSet|False|True}"
Font-Italic="{NotSet|False|True}"
ForeColor="foregroundColor"
BackColor="backgroundColor"
Alignment="{NotSet|Left|Center|Right}"
StyleReference="styleReference"
Visible="{True|False}"
Wrapping="{NotSet|Wrap|NoWrap}"
BackLabel="BackLabel"
FormToValidate="FormID"
HeaderText="HeaderText">
</mobile:ValidationSummary>

Properties


Table 4-1 for details of those properties that are inherited from MobileControl.)





















Table 5-11: Significant Properties of the ValidationSummary Control


Property


Type


Description


BackLabel


String


If this property has a value, it is used for the text of a link that takes the user back to the input Form control to try to reenter text.


FormToValidate


String


The ID of the form to validate.


HeaderText


String


The title that precedes the list of error messages on the validation page. This property is displayed at the head of the page in HTML renderings and preceding each error message in WML browsers.






Warning

The ValidationSummary control uses the value of the ErrorMessage property of each validation control. Each validation control also displays an inline error if its Display property isn't set to None. If the Text property of the validation control has a value, however, that value is displayed instead of the ErrorMessage property. The ValidationSummary control ignores the value of the Text attribute of the validation controls and always uses the ErrorMessage property in the validation summary.


Using the ValidationSummary Control


Listings 5-18 and 5-19 prompt the user to enter his or her name and password in a form. When the form data posts to the server, the ValidationSummary control provides a summary of all validation errors.

Listing 5-18: Source for SummaryExample.aspx






<%@ Page Inherits="MSPress.MobWeb.SumEx.SummaryExample"
CodeBehind="SummaryExample.aspx.cs"
Language="C#"%>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label id="Label1" runat="server">
Your name:
</mobile:Label>
<mobile:TextBox id="userName" runat="server"/>
<mobile:Label id="Label2" runat="server" >
Password
</mobile:Label>
<mobile:TextBox id="password" runat="server" Password="True"/>
<mobile:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server"
ControlToValidate="userName"
Display="None"
ErrorMessage="Your name is required!"/>
<mobile:RequiredFieldValidator id="RequiredFieldValidator2"
runat="server"
ControlToValidate="password"
Display="None"
ErrorMessage="A password is required!"/>
<mobile:Command id="Command1" runat="server" OnClick="Command1_Click">
Submit
</mobile:Command>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:ValidationSummary id="ValidationSummary1"
runat="server"
HeaderText="Missing Values:"
FormToValidate="Form1"
BackLabel="Retry"/>
</mobile:Form>
<mobile:Form id="Form3" runat="server">
<mobile:Label runat="server">
Error free submission.
</mobile:Label>
</mobile:Form>












Listing 5-19: Code-behind file SummaryExample.aspx.cs






using System;
namespace MSPress.MobWeb.SumEx
{
public class SummaryExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.Form Form2;
protected System.Web.UI.MobileControls.Form Form3;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Command1.Click +=
new System.EventHandler(this.Command1_Click);
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form3;
}
else
{
ActiveForm = Form2;
}
}
}
}











Figure 5-9 shows this summary displayed on the Nokia simulator.


Figure 5-9: ValidationSummary output showing multiple submission errors


Validation Controls Example


The validation scenarios we've presented so far have been rather limited. This next code sample is a bit more challenging. It demonstrates the type of validation you're likely to perform in a real mobile Web application.

Listings 5-20 and 5-21 display a form that collects information for an online charitable donation. When the user submits the form, full validation occurs. Figure 5-10 shows how this form will look if the user doesn't supply any data.


Figure 5-10: The page the validation controls example returns, indicating that the user made multiple submission errors

You should be aware of the following three issues when examining this sample application:



Each input control uses multiple validation controls.



The RequiredFieldValidator control validates each input control first.



The program reports validation errors next to a control when the message is important; otherwise, the code places the message in the validation summary.



Listing 5-20: Source for ValidationExample.aspx






<%@ Page Inherits="MSPress.MobWeb.ValEx.ValidationExample"
CodeBehind="ValidationExample.aspx.cs" Language="c#" %>
<%@ Register TagPrefix="mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>
<mobile:Form id="Form1" runat="server">
<mobile:Label runat="server" BreakAfter="false">
E-mail address:
</mobile:Label>
<mobile:TextBox id="email1" runat="server"/>
<mobile:RequiredFieldValidator id="RequiredFieldValidator1"
runat="server"
ErrorMessage="E-mail address required"
ControlToValidate="email1"
Display="None"/>
<mobile:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server"
ControlToValidate="email1"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([- .]\w+)*">
Not a valid e-mail address
</mobile:RegularExpressionValidator>
<mobile:Label id="Label2" runat="server" BreakAfter="false">
Re-type e-mail
</mobile:Label>
<mobile:TextBox id="email2" runat="server"/>
<mobile:RequiredFieldValidator id="RequiredFieldValidator2"
runat="server"
ErrorMessage="You must re-type e-mail"
ControlToValidate="email2"
Display="None"/>
<mobile:CompareValidator id="CompareValidator1"
runat="server"
ErrorMessage="E-mail addresses do not match. "
ControlToValidate="email2"
ControlToCompare="email1"
Display="None"/>
<mobile:Label id="Label3" runat="server" BreakAfter="false">
Donation (min. $5)
</mobile:Label>
<mobile:TextBox id="donation" runat="server" Password="True"/>
<mobile:RequiredFieldValidator id="RequiredFieldValidator3"
runat="server"
ErrorMessage="You must enter an amount"
ControlToValidate="donation"
Display="None"/>
<!-- The RangeValidator Control requires that a maximum value is set.
This value could represent the payment ceiling accepted by the
online payment service provider -->
<mobile:RangeValidator id="RangeValidator1"
runat="server"
ControlToValidate="donation"
Type="Currency"
MinimumValue="5"
MaximumValue="1000">
Minimum donation is $5
</mobile:RangeValidator>
<mobile:Command id="Command1" runat="server">
Donate!
</mobile:Command>
<mobile:ValidationSummary id="ValidationSummary1"
runat="server"
FormToValidate="Form1"/>
</mobile:Form>
<mobile:Form id="Form2" runat="server">
<mobile:Label id="Label4" runat="server">
Thank you for donating.
</mobile:Label>
</mobile:Form>












Listing 5-21: Code-behind file ValidationExample.aspx.cs






using System;
namespace MSPress.MobWeb.ValEx
{
public class ValidationExample : System.Web.UI.MobileControls.MobilePage
{
protected System.Web.UI.MobileControls.Label Label1;
protected System.Web.UI.MobileControls.TextBox email1;
protected System.Web.UI.MobileControls.RequiredFieldValidator
RequiredFieldValidator1;
protected System.Web.UI.MobileControls.RegularExpressionValidator
RegularExpressionValidator1;
protected System.Web.UI.MobileControls.Label Label2;
protected System.Web.UI.MobileControls.TextBox email2;
protected System.Web.UI.MobileControls.RequiredFieldValidator
RequiredFieldValidator2;
protected System.Web.UI.MobileControls.CompareValidator
CompareValidator1;
protected System.Web.UI.MobileControls.Label Label3;
protected System.Web.UI.MobileControls.TextBox donation;
protected System.Web.UI.MobileControls.RequiredFieldValidator
RequiredFieldValidator3;
protected System.Web.UI.MobileControls.RangeValidator
RangeValidator1;
protected System.Web.UI.MobileControls.Command Command1;
protected System.Web.UI.MobileControls.ValidationSummary
ValidationSummary1;
protected System.Web.UI.MobileControls.Form Form1;
protected System.Web.UI.MobileControls.Label Label4;
protected System.Web.UI.MobileControls.Form Form2;
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Command1.Click +=
new System.EventHandler(this.Command1_Click);
}
protected void Command1_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
ActiveForm = Form2;
}
}
}
}











/ 145