使用CustomValidator验证
CustomValidator 是一个提供灵活验证方式的控件,它也能在客户端和服务器端验证,分别提供了两种验证的方法原型:
服务器端验证:
void ServerValidation (object source, ServerValidateEventArgs args)
客户端验证(js):
function ValidationFunctionName(source, arguments)
javascript 函数 和 CustomValidator控件相结合使用
<asp:TextBox runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" ClientValidationFunction="CheckPwd" ControlToValidate="txtPwdPrompt" ErrorMessage="<span style='font:12px'>提示问题必须在2-50个字符内</span>" Display="None"></asp:CustomValidator>
Javascript函数:
<script>
function CheckPwd(source, arguments)
{
if(arguments.Value.Length>2 || arguments.Value.Length < 50)
{
arguments.IsValid=true;
}
else
{
arguments.IsValid =false;
}
}
</script>
函数有两个参数:
source 参数是对为 CustomValidator 控件呈现的 <span> 元素的引用。因此,您可以编程的方式控制 <span> 标记,如修改 InnerHtml 属性。
arguments 参数是一个具有以下两个属性的对象:Value 和 IsValid。使用此参数可以获取控件的值,以根据自定义验证例程验证并指示该值是否有效。
使用 ClientValidationFunction 属性指定与 CustomValidator 控件关联的客户端验证脚本函数的名称。由于该脚本函数在客户端执行,因此该函数必须使用目标浏览器支持的语言(如 VBScript 或 JScript)来编写。
与服务器端验证一样,可以通过使用 arguments 参数的 Value 属性来访问要验证的输入控件中的字符串。通过设置 arguments 参数的 IsValid 属性返回验证结果。