Você está na página 1de 46

VALIDATION CONTROLS

 Each validator is associated with a single input control, but you


can associate two or more validators with same input control
 ASP.NET provides six validation controls:
■ RequiredFieldValidator - checks that an entry has been
made.
■ CompareValidator - Checks an entry against a constant
value or the value of another control. Can also be used
to check for specific data type
■ RangeValidator - Checks that an entry is within a
specified range
■ RegularExpressionValidator - Checks that an entry
matches a pattern that’s defined by a regular expression
■ CustomValidator - Checks an entry using validation code
that you write yourself
■ ValidationSummary - Displays a summary of error
messages from the other validation controls

2
Property Description
ControlToValidate The ID of the control to be validated

Display
Determines how error message is to be displayed
(i.e. static, dynamic or none)
ErrorMessage
The message that is displayed in the validator and/or
the validation summary control when the validation
fails
Text the message that’s displayed in the validator when
ErrorMessage property is used to display a message in
the validation summary control

Enabled Indicates whether the validation control is enabled


EnableClientScript Indicates whether validation will be done in client
ValidationGroup Indicates which group the validation control is a part
of
IsValid
Indicates whether the control specified in the
QflUtfeQflMMpte flfflBfffty passed he validation
The required field validator checks that the user
entered data into an input control.

 Additional property:
■ InitialValue: describes the initial value of the
control that’s validated. If the value does not
isn’t changed, the validation fails. The default is
an empty string

Example:
 A required field validator that checks for a
required entry
 Name:
<asp:TextBox ID="txtname" runat=”server“
Width="266px"></asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server“
ErrorMessage="you must enter your name“
ControlToValidate="txtname">
</asp:RequiredFieldValidator>
 A required field validator that checks that an
initial value is changed:
Birth Date:
<asp:TextBox ID="txtBirthDate“ runat="server">
mm/dd /yyyy< / asp: TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server“
ControlToValidate="txtBirthDate" InitialValue =
"mm/dd/yyyy“
ErrorMessage="you must enter a birth
date"></asp:RequiredFieldValidator>
 A required field validator that forces an option to be
chosen from the listbox
<asp:ListBox ID="lstCardType" runat="server">
<asp:ListItem Selected= "True" Value="none">--
Select a Card Type--</asp:ListItem>
<asp:ListItem>Visa</asp:ListItem>
<asp:ListItem>MasterCard</asp:ListItem>
<asp:ListItem>AmericanExpress</asp:ListItem>
</asp:ListBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator3" runat="server"
ErrorMessage="you must select a credit card
type" ControlToValidate="lstCardType"
InitialValue="none"></asp:RequiredFieldValidator>

7
 The compare validator compares the value
entered into a control with a constant value
or with the value entered into another control.
 It can also be used to check if the user enters
a specific kind of data
Property Description
ValueToCompare
The value that the control specified in the
ControlToValidate property should be compared
to
Operator
The type of comparison to perform (Equal,
NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, or DataTypeCheck)
Type
The datatype to use for the comparision
(String, Integer, Double, Date or Currency)
ControlToCompare
The ID of the control that the value of the
control specified in the ControlToValidate
Property should be compared to.
 A compare validator that checks for a value
greater than zero:
<asp: TextBox ID="txtQuantity“ runat="server">
</asp:TextBox> &nbsp;
<asp: CompareValidator ID="CompareValidator1“
runat="server“ ControlToValidate ="txtQuantity“
Type="Integer" Operator="GreaterThan“
ValueToCompare="0"
ErrorMessage="Quantity must be greater than
zero">
</asp:CompareValidator>

10
 A compare validator that checks for an integer
value
<asp: TextBox ID="txtQuantity“ runat="server">
</asp:TextBox> &nbsp;
<asp: CompareValidator ID="CompareValidator2“
runat="server“ ControlToValidate="txtQuantity“
Operator="DataTypeCheck" Type="Integer“
ErrorMessage="Quantity must be an integer">
</asp:CompareValidator>
 A Compare Validator that compares the values of
two textboxes
<asp: TextBox ID="txtStartDate" runat="server">
</asp:TextBox> <br/>
<asp: TextBox ID="txtEndDate" runat="server">
</asp:TextBox> <br/>
<asp: CompareValidator ID="CompareValidator3"
runat="server“ ControlToValidate="txtEndDate"
Operator="GreaterThan" Type="Date"
ControlToCompare="txtStartDate"
ErrorMessage="end date must be greater than
start date">
</asp:CompareValidator>
 The Range Validator checks that the user enters
a value that falls within the range specified by the
Minimum value and Maximum Value Properties
which can be set when range validator is created
or when the page is loaded.
 If the user enters a value that can’t be converted
to the correct data type, the validation fails.
 If the user doesn’t enter a value into the
associated input control, the range validator
passes its validation test. So, provide a required
field validator if a value is required.
 Additional Properties of the Range Validator

Properties Description
MinimumValue The Minimum value allowed for
the control
MaximumValue The maximum value allowed for
the control
Type The data type to use for the
comparision (String,
Integer,
Double, Date or Currency)
 A range validator that checks for a numeric
range:
<asp: TextBox ID="txtDays" runat="server">
</asp:TextBox>&nbsp;
<asp: RangeValidator ID="RangeValidator1“
runat="server"
ControlToValidate="txtDays"
Type="Integer“ MaximumValue=“14“
MinimumValue="1"
ErrorMessage="Days must be between 1 and 14">
</asp: RangeValidator>
 A range Validator that checks a date range
that's set at run time
<asp: TextBox ID="txtArrival“
runat="server">01 /01/12</asp:TextBox>&nbsp;
<asp: RangeValidator ID="valArrival" runat="server"
ControlToValidate="txtArrival" Type="Date“
ErrorMessage="you must arrive within 30 days">
</asp: RangeValidator>
 Code that sets the minimum and maximum
values when the page is loaded
protected void Page_load(Object sender, EventArgs
e)
{
if(!IsPostBack)
{
valArrival.MinimumValue =
DateTime.Today.ToShortDateString();
valArrival.MaximumValue =
DateTime.Today.AddDays(30).ToShortDateString()

}
}
 Validation summary control displays a summary
of error messages that were generated by the
page’s validators.
 The summary can be displayed on the webpage
or in a separate message box.
 The error messages displayed in the validation
summary control come from the ErrorMessage
property of the page’s validators.
 To set the different message in the validator set
it’s text property of the validator.
 Set the display property of the validator control
to none if u do not wish to display an error
message
 Additional Properties of Validation Summary
Control:
P roperty Description
DiaplayMode
Specifies how the error messages from the
validation controls are to be displayed.
(BulletecList, List or SingleParagraph. Default is
BulletedList)
HeaderText
The text that’s displayed before the list of error
messages
ShowSummary
A boolean value that determines whether the
validation summary should be displayed on the
web page. The default is True
ShowMessageBox
A boolean value that determines whether the
validation summary should be displayed in a
message box. Default is false.
 Two Validators and a validation summary
control that's diaplaved on the web page
<asp: RequiredFieldValidator ID="RequiredFieldValidator1“
runat="Server“ ControlToValidate^'lstCardType"
InitialValue="None"
ErrorMessage="you must select credit card type"
display= "dynamic">*</asp: RequiredFieldValidator>

<asp: RequiredFieldValidator ID="RequiredFieldValidator2“


runat="Server“ ControlToValidate="txtCardNumber"
ErrorMessage="you must enter a credit card number"
display= "dynamic">*</asp: RequiredFieldValidator>

<asp: ValidationSummary ID="ValidationSummary1"


runat="server"
HeaderText="Please Correct the following Errors"/>
 If the browser DHTML, the validation controls do
their validation on the client using client side
script.
 Validation is performed on the client side when
the focus leaves the input control. (exception:
RequiredFieldValidator)
 In case if the browser doesn’t support DHTML,
validation is done on the server on the click of a
button whose CasuesValidation property is set to
True.
 If a validation control indicates invalid data, the
“IsValid” property of the control & page is set to
false.
 To perform validation on server set
“EnableClientScript” property of validation
controls to false.
 Additional Property:
 ■ ValidationExpression: a string that specifies a
regular expression. The regular Expression
defines a pattern that the input data must match
to be valid.
 ASP.NET provides several standard regular
expressions that you can access using Regular
Expression Editor like phone nos, internet
email address’s, postal codes etc.
 Custom expressions can be created based on
regular expressions
 Regular Expression editor dialogue Box
 A regular expression validator that validates five
digit numbers
<asp: TextBox ID="txtZipcode"
runat="server"></asp:TextBox>&nbsp;
<asp: RegularExpressionValidator
ID="RegularExpressionValidator1"
runat="server" controlTOValidate="txtZipcode"
ValidationExpression="\d{5}”
ErrorMessage="must be a five digit U.s zip code">
</asp: RegularExpressionValidator>
 A regular expression validator that validates U.S
phone numbers
<asp: TextBox ID="txtPhone"
runat="server"></asp:TextBox>&nbsp;
<asp: RegularExpressionValidator
ID="RegularExpressionValidator2"
runat="server" controlTOValidate="txtPhone"
Val1dat1onExpressi'on="((\(\d{3}\) ?) | (\d{3}-
))?\d{3}-\d{4}" ErrorMessage="must be a five digit
U.s zip code">
</asp: RegularExpressionValidator>
 Common regular expression elements:
Element Description
Ordinary Matches any character other than , , $, A, [ , {, (, |, ) , *, +,
Character ?, or \
\ Matches any character that follows
\d Matches any decimal digit
\D Matches any decimal character other than decimal digits
\w Matches any word character (a-z, A-Z and 0-9)
\W Matches any character other than the word character
\s Matches any whitespace character (space, tab, newline etc.)
\S Matches any character other than white space character
[abcd] Matches any character included between the brackets

27
 Common regular expression elements:
Element Description
[Aabcd]
Matches any character that is not included between the
brackets
[a-z] Matches any characters in the indicated range
{n}
Matches exactly n occurrences of the preceding element or
group
{n,}
Matches at least n occurrences of the preceding element or
group
{n,m}
Matches at least n but no more than m occurrences of the
preceding element or group
*

Matches zero or more occurrences of the preceding element


or group
 Common regular expression elements:
Element Description
?
• Matches zero or one occurrence of the preceding element or
group
+
Matches one or more occurrences of the preceding element
or group
| Matches any elements separated by a vertical bar
() Groups the elements that appear between the parentheses
 Examples
Expression Example
\d{3} 289
\w{8,20} Frankenstein
\d{2}-\d{4} 10-3944
\w{1,8}.\w{1,3} freddy.jpg
(AB) | (SB) - \d{1,5} SB-3276
\d{5}(-\d{4})? 93711-2765
\w*\d\w* Arm01

[xyz]\d{3} x023
 You can use the custom validator to validate
the input data using the validation tests you
specify.
 Validation is performed using the custom
validator’s ServerValidate event.
 ServerValidate event is available with 2
arguments
■ Object
■ ServerValidateEventArgs (can be used to access
the value provided by the user
 Properties of ServerEventManagementClass:
■ Value: the text string to be validated
■ IsValid: A boolean property that you set to TRUE
if the value passes the validation test or FALSE
otherwise

32
 Aspx code for the custom validator:
<asp: TextBox ID="txtPrductCode"
runat="server">
</asp:TextBox>&nbsp;
<asp:CustomValidator id="valProductCode"
runat="server"
ContorlToValidate="txtProduxtCode"
ErrorMessage="product code must be in
database" OnServerValidate=
“valProductsCode_ServerValidate">
</asp: CustomValidator>
 C# code for Custom Validator:
protected void
valProducts_ServerValidate(Object source,
ServerValidateEventArgs args)
{
args.IsValid =
HalloweenDB.CheckProductsCode(args.Value);
}

34
 A validation group is a group of validators that
are run when the page is posted.
 To group validators, set the Validation group
attribute for each control that causes a postback
to specify which group should be executed.
 You can use C# code to force the execution of
specific validation group by using the
Page.Validate method with the validation group
name as the argument.
 Any validation that doesn’t specify the
ValidationGroup attribute are a part of the
default group. This group is executed when
started by a button or control that doesn’t
specify a validation group or when the page
validate method is used without an argument.
 Attributes that cause group validation when
a button is clicked:
■ CausesValidation: specifies whether validation
should be performed when the user clicks the
button.
■ ValidationGroup: specifies the name of the group
to be validated if CausesValidation is TRUE.
 A text box with a validator that specifies a
validation group:
<asp: TextBox ID="txtShipToName“
runat="Server" />
<asp: RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server“
ControlToValidate="txtShipToName“
ErrorMessage="you must enter a ship to name“
ValidationGroup="ShipTo">
</asp:RequiredFieldValidator>

37
38

Você também pode gostar