1

我是验证新手,我创建了一个简单的 web 表单,我正在尝试验证,我在其中覆盖了 App_Code 文件夹EvaluateIsValid()中类的方法。BaseValidator在这种方法中,我在调用设置字符串时收到错误Object is not set to an instance of an object 。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 >但无济于事。

有什么想法我哪里出错了吗?

4

1 回答 1

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()
        {

        }
    }
}

这就是它的全部内容!

于 2012-10-25T18:39:16.817 回答