TextBox自定义Web控件和JavaScript客户端验证

时间:2013-11-18 09:43:09

标签: c# javascript asp.net custom-controls

我创建了自定义Web控件文本框,工作正常,代码如下:

public class ReqTextBox : TextBox
{
    private RequiredFieldValidator req;
    public string ErrMsg { get; set; }

    protected override void OnInit(EventArgs e)
    {
        this.CssClass = "inp-form";
        req = new RequiredFieldValidator();
        req.ControlToValidate = this.ID;
        req.ErrorMessage = string.IsNullOrEmpty(this.ErrMsg) ? "*" : this.ErrMsg;
        req.Display = ValidatorDisplay.Dynamic;
        //req.EnableClientScript = true;
        if (!string.IsNullOrEmpty(this.ValidationGroup))
            req.ValidationGroup = this.ValidationGroup;
        Controls.Add(req);
        //base.OnInit(e);
    }

    protected override void Render(HtmlTextWriter w)
    {
        base.Render(w);
        req.RenderControl(w);
    }
}

以下代码可以正常使用:

    <Mas:ReqTextBox runat="server" ID="txtCustBankCode" Width="236px" ValidationGroup="vmas" ErrMsg="Enter BankName"></Mas:ReqTextBox>

<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />

这里工作正常。现在,如果我在按钮上添加onclientclick事件,那么它将不会检查文本框是否为空。在Valid()函数中返回true和false都不起作用。

<asp:ImageButton runat="server" ID="ibtnUpdate" OnClick="ibtnUpdate_Click" ToolTip="Update" AlternateText="Update" onClientClick="return Valid();" ImageUrl="../Resources/Images/Update2.gif" ValidationGroup="vmas" />

我错过了什么......?

req.EnableclientScript = true/false;

没帮我。 需要帮忙。 感谢。

EDIT: I need to use this Customcontrol, so that user need to enter some data and for those entered data, i need to validate with javascript function. Sorry for late EDIt.

1 个答案:

答案 0 :(得分:0)

将customvalidator与自定义客户端验证功能一起使用:

    <script type="text/javascript">
        function ClientValidate(source, arguments) {
            if (arguments.Value === "foo") {
                arguments.IsValid = true;
            } else {
                arguments.IsValid = false;
            }
        }
    </script>

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator1" runat="server" 
          ErrorMessage="Invalid entry" ControlToValidate="TextBox1"
          ClientValidationFunction="ClientValidate"></asp:CustomValidator>

    <asp:Button ID="Button1" runat="server" Text="Button" />

here了解详情。