如何客户端验证自定义控件?

时间:2012-05-10 18:15:53

标签: c# asp.net validation client-side

关于我的previous question关于自定义控件和验证,我现在已经进行了服务器端验证,但似乎无法弄清楚如何添加客户端验证。我必须遵循控制:

[ValidationProperty("Text")]
[ToolboxData("<{0}:DateSelect runat=server></{0}:DateSelect>")]
public class DateSelect : System.Web.UI.WebControls.Panel
{
 private DropDownList day;
 private DropDownList month;
 private DropDownList year;

 public DateSelect()
 {
    day = new DropDownList();
    /* some code to create items for 'day' here */
    Controls.Add(day);
    month = new DropDownList();
    /* some code to create items for 'month' here */
    Controls.Add(month);
    year = new DropDownList();
    /* some code to create items for 'year' here */
    Controls.Add(year);
 }


 public string Text
 {
    get
    {
        return year.Text + "-" + month.Text + "-" + day.Text;
    }
 }
}

在我的webform上添加此Control,在DataType操作中添加CompareValidator以检查有效日期。我将验证程序的EnableClientScript设置为false,并且在服务器端验证了自定义控件,并在正确的情况下提供了正确的消息。但是,只要我将EnableClientScript转为true,自定义控件就会在客户端验证,并在DropDownLists中实际存在有效日期时生成错误消息。我一直在试图弄清楚为什么并最终得到.net生成的以下javascript,我认为永远不会想出正确的值:

function ValidatorGetValueRecursive(control)
{
    if (typeof(control.value) == "string" && (control.type != "radio" || control.checked == true)) {
        return control.value;
    }
    var i, val;
    for (i = 0; i<control.childNodes.length; i++) {
        val = ValidatorGetValueRecursive(control.childNodes[i]);
        if (val != "") return val;
    }
    return "";
}

所以我相信我必须在我的自定义控件中添加一些东西,也许是一段javascript,一旦验证器尝试验证我的控件并生成正确的值以从三个选定项中进行验证,就会调用它DropDownLists。我不知道在哪里添加这个脚本。有什么指针吗?

1 个答案:

答案 0 :(得分:1)

因为您的控件实际上包含多个服务器控件,所以我建议将客户端验证器添加到控件集合中,就像您正在使用其他控件一样。

var ddl = new DropDownList();
ddl.ID = "ddlDay";
Controls.Add(ddl);

var validator = new RequiredFieldValidator();
val.ControlToValidate = ddl.ID;
val.ErrorMessage = "*"; //property to set this for all validators
val.Display = ValidatorDisplay.Dynamic; //property to set this for all validators
Controls.Add(validator);

添加验证器后,您可以公开属性以应用于控件中的所有验证器,如验证组,错误消息,显示类型等。

编辑#1

如果要将组合输入验证为一个,请使用CustomValidator并通过控件注册必要的客户端脚本。

我根本没有测试过这个,但下面是一个简单的代码示例来演示这个概念。显然,您将使用StringBuilder或其他内容在代码中构建验证函数:

<script type="text/javascript">
    clientValidate = function(source, args){

        var ddl1 = document.getElementById("<%= ddl1.ClientID %>");
        var ddl2 = document.getElementById("<%= ddl2.ClientID %>");

        if (ddl1.options[e.selectedIndex].value.length == 0)
            args.IsValid = false;
        if (ddl2.options[e.selectedIndex].value.length == 0)
            args.IsValid = false; 

    }
</script>
<asp:CustomValidator ID="MyCustomValidator" runat="server"
    ErrorMessage="Invalid" 
    ClientValidationFunction="clientValidate" />

以下是一些解释如何使用自定义验证器进行客户端验证的文章:

编辑#2

更多阅读表明CustomValidator应与您的复合控件兼容。