Saturday, July 17, 2010

How to validate set of asp.net controls based on a condition - Asp.net

Cause: While having validators disabled in the clientside still get Page.IsValid property is false.

Explanation:
Asp.net validation controls have dual validation mecanisum. One is client side, which is optional and the second one is server side validation, which is mandatory. First in the client side if the clientside validation fails framework block the postback. However clientside validation result will not carried over to the codebehind to populate page.IsValied property but asp.net page life-cycle validate all the validation controls in the serverside and populate the Page.IsValid property. In this senario it does not care that you have set the enable/disable in the client side. Page execution talke all the validators in to account and validate. So it is needed to implement the same logic which you have in client side in the serverside as well and enable disable + set validator.IsValid property to true/false accordingly

However there is a easy way to achive your objective. More framework friendly
  1. Disable client side validation for all your validators.
  2. On page load event enable disable validators accorting to radio button selection
 Here is an example
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script runat="server">
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.rblOption.SelectedValue.Equals("No"))
            {
                this.rvalName.IsValid = true;
                this.rvalName.Visible = false;
            }
            else
                this.rvalName.Visible = true;
        }
        protected void Save(object sender, EventArgs e)
        {
            this.Page.Validate();
            bool valid = this.Page.IsValid;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:RadioButtonList runat="server" ID="rblOption" AutoPostBack="true">
            <asp:ListItem Value="Yes" Selected="True">Yes</asp:ListItem>
            <asp:ListItem Value="No">No</asp:ListItem>
        </asp:RadioButtonList>
        <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
        <asp:RequiredFieldValidator runat="server" ID="rvalName" ControlToValidate="txtName" ErrorMessage="*Required" EnableClientScript="false" />
        <asp:Button runat="server" ID="btnSave" Text="Save" OnClick="Save" />
    </form>
</body>
</html> 

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...