自定义验证对象未设置为实例

时间:2012-10-16 19:56:01

标签: c# webforms customvalidator

我是验证的新手,我创建了一个我正在尝试验证的简单webform,其中我从App_Code文件夹中的EvaluateIsValid()类覆盖了BaseValidator方法。在此方法中,我在this.GetControlValidationValue()调用时收到错误对象未设置为对象的实例以设置字符串。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ValidApp.Default" %>

<!DOCTYPE html>

<script runat="server">
    protected void pageCvd_ServerValidate(object source, ServerValidateEventArgs args)
    {
        ValidApp.App_Code._Validators valid = new ValidApp.App_Code._Validators(usernameTxt.ClientID.ToString());
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="display:inline-block; width:200px;">
        <asp:CustomValidator ID="pageValidatorCvd" runat="server" EnableClientScript="false" OnServerValidate="pageCvd_ServerValidate"></asp:CustomValidator>       
        <asp:Label ID="usernameLbl" runat="server" Text="Username:" style="width:50px; font-size:xx-small"></asp:Label>
        <asp:TextBox ID="usernameTxt" runat="server" style="width:100px; font-size:xx-small"></asp:TextBox>
        <br />
        <asp:Label ID="passwordLbl" runat="server" Text="Password:" style="width:50px; font-size:xx-small"></asp:Label>
        <asp:TextBox ID="passwordTxt" runat="server" style="width:100px; font-size:xx-small"></asp:TextBox> 
    </div>
    <div>
        <asp:Button ID="registryBtn" runat="server" OnCommand="registryBtn_Command" CommandName="" CommandArgument="" Text="Register" style="width:50px; font-size:xx-small"/>
    </div>
    </form>
</body>
</html>

代码背后


namespace ValidApp.App_Code
{
    public class _Validators : BaseValidator
    {
        private string regex;
        private string errorMessage;
        private string controlToValidate;

        protected override bool EvaluateIsValid()
        {
            string value = this.GetControlValidationValue(controlToValidate);
            return Regex.IsMatch(value, regex);
        }

        public _Validators(string controlToValidate = "", string regex = @"^[a-z0-9]{6-8}$", string errorMessage = "The Username is not valid!")
        {
            this.regex = regex;
            this.errorMessage = errorMessage;
            this.controlToValidate = controlToValidate;

            bool validation = EvaluateIsValid();            
        }
    }
}

我试图在<%@ Register >上创建自己的自定义验证,但无济于事。

我出错的任何想法?

1 个答案:

答案 0 :(得分:0)

解决方案:

您似乎无法调用类构造函数,这样EvaluateIsValid()方法会自行命中并获得正确的控制权!

namespace ValidApp.App_Code
{
    public class _Validators : BaseValidator
    {   
        protected override bool EvaluateIsValid()
        {
            string value = this.GetControlValidationValue(ControlToValidate);
            return Regex.IsMatch(value, @"^[a-z0-9]{6-8}$");
        }

        public _Validators()
        {

        }
    }
}

这就是它的全部!