开发者

how to add dynamic custom client side validator in asp.net

i have textbox controls that are created dynamically in the ASP.NET. I want to add dynamically custom validators for these controls. These validators should be run on the client side. I have the following开发者_如何学Go code snippet:

    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());
    }

The method in the javascript will contain the logic. Method InitDynamicControls() is loaded in Page_Load method. When I click the button on the page the validator doesn't run.

can you help me what can be wrong? thanks


Try this:

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

Or even better use this:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜