2

CheckBoxList から 1 つ以上のチェックボックスが選択されているかどうかを検証するように設計された CustomValidator を継承するカスタム バリデータ (CheckBoxListValidator と呼ばれる) があります。サーバー側の検証は期待どおりに機能しますが、クライアント側の検証は起動しません。関数でアラートが発生するかどうかを確認するだけの単純なものを試しましたが、それでも発生しません。コントロールの完全なコードを次に示します。注として、生成された 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