如何在asp.net中添加动态自定义客户端验证器

时间:2011-07-06 17:09:57

标签: javascript asp.net validation

我有在ASP.NET中动态创建的文本框控件。我想为这些控件添加动态自定义验证器。这些验证器应该在客户端运行。我有以下代码段:

    protected override void InitDynamicControls()
    {
        registerScript();

        CustomValidator cv = new CustomValidator();
        cv.ErrorMessage = "error";
        cv.Display = ValidatorDisplay.Dynamic;
        cv.ControlToValidate = TextField.ID;
        cv.ValidationGroup = "ConfigurationValidation";
        cv.ClientValidationFunction = "ConfigurationOption_ClientValidate";

        base.Controls.Add(cv);
    }


    private void registerScript()
    {
        System.Text.StringBuilder script = new System.Text.StringBuilder();

        script.Append("<script language=\"javascript\">\n");
        script.Append("function ConfigurationOption_ClientValidate(source, arguments) \\{arguments.IsValid = false;\\}\n");
        script.Append("</script>\n");

        Type type =  this.GetType();

        if (!Page.ClientScript.IsClientScriptBlockRegistered(type, "ConfigurationOption_ClientValidate"))
            Page.ClientScript.RegisterClientScriptBlock(type, "ConfigurationOption_ClientValidate", script.ToString());
    }

javascript中的方法将包含逻辑。方法InitDynamicControls()在Page_Load方法中加载。当我单击页面上的按钮时,验证器不会运行。

你可以帮我解决什么问题吗? 感谢

1 个答案:

答案 0 :(得分:1)

试试这个:

script.Append("<script type='text/javascript'>");
        script.Append("function ConfigurationOption_ClientValidate(source, arguments) {arguments.IsValid = false; }");
        script.Append("</script>");

或者更好地使用它:

private void registerScript()
{
    Type type = this.GetType();

    if (!Page.ClientScript.IsClientScriptBlockRegistered(type, "ConfigurationOption_ClientValidate"))
        Page.ClientScript.RegisterClientScriptBlock(type, "ConfigurationOption_ClientValidate", "function ConfigurationOption_ClientValidate(source, arguments) { arguments.IsValid = false; }", true);
}