CompareValidator Web 控件可以验证使用者输入的数据,和某个值利用比较运算。其使用语法为:
<ASP:CompareValidator
Id="被程序代码所控制的名称"
Runat="Server"
ControlToValidate="要验证的控件名称"
Operator="DataTypeCheck | Equal | NotEqual | GreaterThan |
GreaterThanEqual | LessThan | LessThanEqual"
Type="资料型别"
ControlToCompare="要比较的控件名称" | ValueToCompare="要比较的值"
ErrorMessage="所要显示的错误信息"
Text="未通过验证时所显示的讯息"
/>
其常用属性说明如下表所示:
下列范例限制使用者所输入的年龄必需大于18 岁:
<Html>
<Form Id="Form1" Runat="Server">
姓名: <ASP:TextBox Id="txtName" Runat="Server"/><br>
年龄: <ASP:TextBox Id="txtAge" Runat="Server"/>
<ASP:CompareValidator Id="Validor1" Runat="Server"
ControlToValidate="txtAge"
ValueToCompare="18"
Operator="GreaterThanEqual"
Type="Integer"
Text="您必须大于十八岁才可以浏览本站"/><br>
住址: <ASP:TextBox Id="txtAdd" Runat="Server"/><br>
<ASP:Button Id="btnOK" Text="确定" OnClick="btnOK_Click"
Runat="Server"/>
<ASP:Label Id="lblMsg" Runat="Server"/>
</Form>
<Script Language="VB" Runat="Server">
Sub btnOK_Click(Sender As Object,e As EventArgs)
If Page.IsValid Then
lblMsg.Text="验证成功!"
End If
End Sub
</Script>
</Html>
下列范例码限制使用者输入必须是整数型态的数据:
<Html>
<Form Id="Form1" Runat="Server">
姓名: <ASP:TextBox Id="txtName" Runat="Server"/><br>
年龄: <ASP:TextBox Id="txtAge" Runat="Server"/>
<ASP:CompareValidator Id="Validor1" Runat="Server"
ControlToValidate="txtAge"
Operator="DataTypeCheck"
Type="Integer"
Text="您必须输入数值"/><br>
住址: <ASP:TextBox Id="txtAdd" Runat="Server"/><br>
<ASP:Button Id="btnOK" Text="确定" OnClick="btnOK_Click"
Runat="Server"/>
<ASP:Label Id="lblMsg" Runat="Server"/>
</Form>
<Script Language="VB" Runat="Server">
Sub btnOK_Click(Sender As Object,e As EventArgs)
If Page.IsValid Then
lblMsg.Text="验证成功!"
End If
End Sub
</Script>
</Html>
上述程序并没有限制使用者一定要输入年龄的数据,若要限制只用者一定要填入数据,可以搭配RequireFieldValidator 来作验证;如下范例所示:
<Html>
<Form Id="Form1" Runat="Server">
姓名: <ASP:TextBox Id="txtName" Runat="Server"/><br>
年龄: <ASP:TextBox Id="txtAge" Runat="Server"/>
<ASP:CompareValidator Id="Validor1" Runat="Server"
ControlToValidate="txtAge"
Operator="DataTypeCheck"
Type="Integer"
Text="您必须输入数值"/>
<ASP:RequiredFieldValidator Id="Validor2" Runat="Server"
ControlToValidate="txtAge"
Text="必填项目"/><br>
住址: <ASP:TextBox Id="txtAdd" Runat="Server"/><br>
<ASP:Button Id="btnOK" Text="确定" OnClick="btnOK_Click"
Runat="Server"/>
<ASP:Label Id="lblMsg" Runat="Server"/>
</Form>
<Script Language="VB" Runat="Server">
Sub btnOK_Click(Sender As Object,e As EventArgs)
If Page.IsValid Then
lblMsg.Text="验证成功!"
End If
End Sub
</Script>
</Html>