简体   繁体   中英

TextBox Custom Web Control and JavaScript Client Validation

I have created custom web control textbox which is working fine and its code is as below:

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

This is working fine with following code:

    <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" />

Here it works fine. Now if i add onclientclick event on button then it will not check if textbox is empty or not. In both return true and false in Valid() function it's not working.

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

What am i missing...?

req.EnableclientScript = true/false;

did not help me. Need Help. Thanks.

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.

Use customvalidator with custom clientvalidation function:

    <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" />

Read more from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM