2

我有一个自定义验证器(称为 CheckBoxListValidator),它继承自 CustomValidator,旨在验证是否从 CheckBoxList 中选择了一个或多个复选框。服务器端验证功能完全符合预期,但客户端验证永远不会触发。我尝试了一些简单的东西,比如函数中的警报,只是为了看看它是否会触发,但即使这样也不会触发。这是控件的完整代码。请注意,我确实在生成的 HTML 中看到了脚本,因此 EnableClientScript 已正确设置。它只是不火。

public class CheckBoxListValidator : CustomValidator //BaseValidator
{        

    /// <summary>
    /// Ensures the control this validator is validating is the proper type.
    /// </summary>
    /// <returns>True if the control being validated is a CheckBoxList, otherwise false.</returns>
    protected override bool ControlPropertiesValid()
    {
        var ctrl = FindControl(this.ControlToValidate);
        return (ctrl != null && ctrl is CheckBoxList);
    }

    protected override bool OnServerValidate(string value)
    {
        return base.OnServerValidate(value);
    }

    /// <summary>
    /// Determines whether this control is in a valid state.
    /// </summary>
    /// <returns>True if one or more items has been selected, otherwise false.</returns>
    protected override bool EvaluateIsValid()
    {
        var clk = this.FindControl<CheckBoxList>(this.ControlToValidate);
        return clk.GetSelectedItems().Count > 0;
    }

    /// <summary>
    /// Attaches the client validation script to the 
    /// rendered page if ClientScript is enabled.
    /// </summary>
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        if (this.EnableClientScript)
            this.CreateClientScript();
    }

    /// <summary>
    /// Creates the client script to validate the control.
    /// </summary>
    private void CreateClientScript()
    {
        this.ClientValidationFunction = "validateCheckboxList";

        StringBuilder sb = new StringBuilder();

        var clk = this.FindControl<CheckBoxList>(this.ControlToValidate);            
        sb.AppendLine("function validateCheckboxList(sender, args) { alert('validateCheckboxList'); args.IsValid = false; }");

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CheckBoxListValidator", sb.ToString(), true);
    }
}
4

0 回答 0