Category Archives: CustomValidator

CustomValidator

[RESOLVED]Client side validation doesnt work

I am trying to validate a control on the client side and change the background of the control. Why is not working

Thank you

<td><asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
                            <asp:CustomValidator ID="CustomValidator1" runat="server" 
                                ErrorMessage="*" ValidateEmptyText="True" SetFocusOnError="True" ControlToValidate="txtName" 
                                ClientValidationFunction="inputValidation"></asp:CustomValidator>
                        </td>
<script type ="text/javascript" src="JavaScript/jquery-1.3.2.min.js">

    function inputValidation(source, args)
    {
        if(args.Value == "")
        {
            source.className = "errorControl";
        }
        else
        {
            source.className = "";
        }
    }


    </script>

Hi,

Try following

It seems that your logic in javascript function is not working. 

refer updated code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .errorControl {
            background-color: Red;
        }
    </style>
    <script type="text/javascript">
        function inputValidation(source, args) {
            if (args.Value == "") {
                document.getElementById(source.controltovalidate).className = 'errorControl';
            }
            else {
                document.getElementById(source.controltovalidate).className = '';
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
            <asp:CustomValidator ID="CustomValidator1" runat="server"
                ErrorMessage="*" ValidateEmptyText="True" SetFocusOnError="True" ControlToValidate="txtName"
                ClientValidationFunction="inputValidation"></asp:CustomValidator>
        </div>
    </form>
</body>
</html>

Regards, Ajay

You need to find the reference of your control first using the source parameter like given below and then change the color of textbox as per your design.

<style>
        .errorControl
        {
            background-color: Red;
        }
    </style>
    <script type="text/javascript">

        function inputValidation(source, args) {
        //Get reference to your control here first
            var ctrl = document.getElementById(source.controltovalidate);
            if (args.Value == "") {
                //source.className = "errorControl";
                if (ctrl) {
                    ctrl.style.background = '#FFAAAA';
                }
            }
            else {
                if (ctrl) {
                    ctrl.style.backgroundColor = '';
                }
                //source.className = "";
            }
        }
    </script>
    <asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="*" ValidateEmptyText="True"
        SetFocusOnError="True" ControlToValidate="txtName" ClientValidationFunction="inputValidation"></asp:CustomValidator>

how to make a Mutually Exclusive CheckBox, Compulsory

Hi all

Is it possible to make a Mutually Exclusive CheckBox, Compulsory?  If so what do I need to use as I can’t see how the  required Field Validator would work on the below?  

<asp:CheckBox ID="chkBoxBPYes" runat="server" Text="Yes" />
   <cc1:MutuallyExclusiveCheckBoxExtender ID="cboBPYesExtender" runat="server" 
      Enabled="True" Key="benefitProtectionChoice" TargetControlID="chkBoxBPYes">
   </cc1:MutuallyExclusiveCheckBoxExtender>
   
<asp:CheckBox ID="chkBoxBPNo" runat="server" Text="No" />
   <cc1:MutuallyExclusiveCheckBoxExtender ID="cboBPNoExtender" runat="server" 
      Enabled="True" Key="benefitProtectionChoice" TargetControlID="chkBoxBPNo">
   </cc1:MutuallyExclusiveCheckBoxExtender>

You can make use of customvalidator function to make the checkbox mandatory like given below.

<script>
            function ValidateCheckBox(sender, args) {
                if ((document.getElementById("chkBoxBPYes").checked == true) || (document.getElementById("chkBoxBPNo").checked == true)) {
                    args.IsValid = true;
                } else {
                    args.IsValid = false;
                }
            }
        </script>
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release"
        CombineScripts="false">
    </asp:ToolkitScriptManager>
  
    <asp:CheckBox ID="chkBoxBPYes" runat="server" Text="Yes" ValidationGroup="btnYes" />
    <asp:MutuallyExclusiveCheckBoxExtender ID="cboBPYesExtender" runat="server" Enabled="True"
        Key="benefitProtectionChoice" TargetControlID="chkBoxBPYes">
    </asp:MutuallyExclusiveCheckBoxExtender>
    <asp:CheckBox ID="chkBoxBPNo" runat="server" Text="No" ValidationGroup="btnYes" />
    <asp:MutuallyExclusiveCheckBoxExtender ID="cboBPNoExtender" runat="server" Enabled="True"
        Key="benefitProtectionChoice" TargetControlID="chkBoxBPNo">
    </asp:MutuallyExclusiveCheckBoxExtender>
    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Required"
        ClientValidationFunction="ValidateCheckBox"></asp:CustomValidator><br />
    <asp:Button ID="Button1" runat="server" Text="Button" />

[RESOLVED]Make Textbox mandatory if radio button is checked, How, please?

Hello again Experts,

I have 2 radio buttons called IsSpecial.

The first radio button has a value of Yes and the other No.

We are trying to determine if a particular product is going to be on promos.

If the user clicks the Yes radio button then promo start date, end date and, promo price become visible so user can fill out these and other boxes.

If the user clicks the No radio button then the form fields mentioned above, startdate, enddate and, promo price, are hidden.

The following code validates most of the form fields except the ones mentioned above.

I am trying to figure out how to NOT validate the form fields that are not visible; only validating them when they are visible.

For instance, if the radio button value of Yes is selected, all visible form fields, including state date, end date and promo price become visible and therefore must be completed. If is skipped, we would like to raise exceptions.

So when completing form fields that are visible, we don't want the hidden form fields to be validated

Any ideas how to handle validating only visible forms but not hidden forms?

BTW: only 4 items can be hidden or visible.

These are pstartdate, penddate, unitprice and txtprice.

Only txtprice is hidden when Yes radio button is selected.

Here is the relevant code I have so far.

Thanks a lot in advance.
 
<head> 
<SCRIPT LANGUAGE="JavaScript"> 
<!-- Begin 
function validate() { 
missinginfo = ""; 
if (document.form.catdescription.value == "0") { 
missinginfo += "n     -  Category CANNOT be blank"; 
} 
if (document.form.pcode.value == "")  { 
missinginfo += "n     -  Product Code CANNOT be blank"; 
} 
if (document.form.pname.value == "") { 
missinginfo += "n     -  Product Name CANNOT be blank"; 
} 
if (document.form.pdescription.value == "") { 
missinginfo += "n     -  Product Description CANNOT be blank"; 
} 
if (( form.IsSpecial[0].checked == false ) && ( form.IsSpecial[1].checked == false )) { 
missinginfo += "n     -  please check Yes or No"; 
} 
if ((document.form.pphoto.value == "") || (document.form.pphoto.value == "NA")) 
 { 
missinginfo += "n     -  Photo is either blank or does not contain NA"; 
} 
if (document.form.file2.value == "") { 
missinginfo += "n     -  Browse a picture to upload"; 
} 
 
if (missinginfo != "") { 
missinginfo ="_____________________________n" + 
"Please ensure that:n" + 
missinginfo + "n_____________________________" + 
"nPlease re-enter and submit again!"; 
alert(missinginfo); 
return false; 
} 
else return true; 
} 
//  End --> 
</script> 
<script type="text/JavaScript"> 
<!-- Begin 
function ChangeDiv(id) 
{ 
if(id == "No") 
{ 
document.getElementById('nof').style.display = "block"; 
document.getElementById('yesf').style.display = "none"; 
} 
else 
{ 
document.getElementById('nof').style.display = "none"; 
document.getElementById('yesf').style.display = "block"; 
} 
} 
//  End --> 
</script> 
</head> 
  <table>
     <tr>
      <td class="body1" div align="right">Product Code:</td>
      <td width="73%"><input type="text" name="pcode"></td>
    </tr>
    <tr>
      <td class="body1" div align="right">Product Name:</td>
      <td><input type="text" name="pname"></td>
    </tr>
    <tr>
      <td class="body1" div align="right">Product Description:</td>
      <td> <textarea name="pdescription" cols="30" rows="5" value="<%=strUserText%>"></textarea>
    </tr>
    <tr>
      <td nowrap>Is product on PROMOS?</td>
      <td>
       <INPUT Type=Radio Name="IsSpecial" Value="Yes" onClick="ChangeDiv('Yes')">Yes<br>
       <INPUT type="Radio" name="IsSpecial" value="No" onClick="ChangeDiv('No')">No
     </td>
   </tr>
   </TABLE>
   </TD>
   <TD VALIGN="CENTER" ALIGN=CENTER >

   <TABLE BORDER=0 CELLSPACING=0 CELLPADDING=4 BORDERCOLOR="YELLOW" >
    <tr>
    <td class="body1" div align="right">
       <div id="yesf" style="display:none;">
       Promo Start Date:
      <input type="text" name="pstartdate" class="normaltxt"><br>
       Promo End Date:
      <input type="text" name="penddate" class="normaltxt"><br>
       PROMO Price:
	  <input type="text" name="txtsprice" value="">
	  </div></td>
    </tr>
    <tr>
     <td class="body1" div align="right">
     <div id="nof">
      Regular Price:
      <input type="text" name="unitprice" value="">
        </div></td>
    </tr>
    <tr>
      <td class="body1" div align="right">Photo:
      <input type="text" name="pphoto" value=""></td>
    </tr>
    <tr>
      <td div align="right">How many in stock:
      <input type="text" name="cstock" value=""></td>
    </tr>
    <tr>
     <td class="body1" div align="right">Attach for IMG folder:</div>
     <INPUT NAME="file1" TYPE="FILE" value="" SIZE=30></td>
    </tr>
    <tr>
     <td class="body1" div align="right">Attach for SMALL folder:</div>
     <INPUT NAME="file2" TYPE="FILE" value="" SIZE=30></td>
    </tr>
   </table>
  </td>
 </tr>
 </table>
 <hr color="silver">

  <table width="100%" border="0" cellspacing="4" cellpadding="4">
    <tr>
      <td><div align="center">
       <input  type="image" name="submit" id="submit2" title="submit to db." border="0" src="images/submitbutton.jpg" width="142" height="47" alt="Submit Button">
       </div></td>
    </tr>
  </table>

hi

try this

if IsSpecial.value = "Yes"{

  YourRequiredValidator.Enabled = true ;

}

or

based on event  your this

  YourRequiredValidator.Enabled = (yourcondition)? true : false;

refer here for more info.

http://forums.asp.net/t/617760.aspx

http://www.a2zmenu.com/Blogs/AspNet/How-to-invoke-ASP.NET-validators-on-demand.aspx

Thanks,

Thanks good people.

 

I was able to resolve this by handling it a bit differently.

The code that solved it:

//First make sure a radio button is selected

if (( myForm.IsSpecial[0].checked == false ) && ( myForm.IsSpecial[1].checked == false )) {
missinginfo += "n     -  please check Yes or No";
}

//Then, if the NO radio button is checked, then no promo; validate only Regular Price
if (( myForm.IsSpecial[0].checked == false ) && ( myForm.IsSpecial[1].checked == true )) {
   if (document.myForm.unitprice.value == "") {
     missinginfo += "n     -  Please Regular Price amount";
   }
}

//Finally, if the YES radio button is checked, then this product is on promo, ensure promo start date, end date and promo price is entered.
if (( myForm.IsSpecial[0].checked == true ) && ( myForm.IsSpecial[1].checked == false )) {
   if (document.myForm.pstartdate.value == "") {
     missinginfo += "n     -  Please enter PROMO Start Date";
   }
   if (document.myForm.penddate.value == "") {
     missinginfo += "n     -  Please enter PROMO End Date";
   }
   if (document.myForm.txtsprice.value == "") {
     missinginfo += "n     -  Please enter PROMO amount";
   }
}
 
Again, thanks for attempting to help me.

[RESOLVED]CustomValidator access OnServerValidate in Code behind

Hi

I have two web user controls say uc1.ascx and uc2.ascx. uc2 is inside uc1. There is a custom validator in uc2 and i want it’s server side validation mathod in uc1. Is it possible..?

See my sample code:

uc1.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uc1.ascx.cs" Inherits="uc1" %>
<%@ Register TagPrefix="uc2" TagName="usercontrol" Src="uc2.ascx" %>

<uc2:usercontrol runat="server" ID="uc2"></uc2:usercontrol>
<asp:TextBox ID="txtTotalAmount" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />

uc1.ascx.cs

protected void Page_Load(object sender, EventArgs e)
{
     CustomValidator ValidateFinalAmount = (CustomValidator) uc2.FindControl("ValidateFinalAmount");
     ValidateFinalAmount.ServerValidate += new ServerValidateEventHandler(
     ValidateFinalRefundAmount_ServerValidate);
}

void ValidateFinalRefundAmount_ServerValidate(object source, ServerValidateEventArgs args)
{
     TextBox txtItemAmount = (TextBox)uc2.FindControl("txtItemAmount");
     if (Convert.ToDouble(txtItemAmount.Text) > Convert.ToDouble(txtTotalAmount.Text))
     args.IsValid = false;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
     if (Page.IsValid)
     {
          //code
     }
}

uc2.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="uc2.ascx.cs" Inherits="uc2" %>
<asp:TextBox ID="txtItemAmount" runat="server"></asp:TextBox>
<asp:customvalidator id="ValidateFinalAmount" runat="server" display="Dynamic"
validationgroup="validationGroup1" 
errormessage="The sum of the the item amount applied cannot exceed the total amount."
controltovalidate="txtItemAmount" />

This is just a sample code.

I want server side validation in uc1 because there are some limitations I am facing when have it in uc2.

Please give me some solution.

Thanks

Kamini

Put your validation code in a base class and make both of your controls inherit that class.  That way the web controls will both have access to the code.

Hi kaminitandel

I’m very glad for reply your question.

According to your description and your code, you can add a ServerValidateEventHandler instance at the uc2.ascx.cs. It will serve as an event appears in the uc1.ascx. 

The following code is a rewrite of the code according to your

uc1.ascx code

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="uc1.ascx.cs" Inherits="DemoCustomValidation.UserControl.uc1" %>
<%@ Register TagPrefix="uc2" TagName="usercontrol" Src="uc2.ascx" %>

<uc2:usercontrol runat="server" ID="uc2" OnCustomer_ServerValidate="ValidateFinalRefundAmount_ServerValidate"></uc2:usercontrol>
<asp:TextBox ID="txtTotalAmount" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />

uc1.ascx.cs code

protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void ValidateFinalRefundAmount_ServerValidate(object source, ServerValidateEventArgs args)
        {
            TextBox txtItemAmount = (TextBox)uc2.FindControl("txtItemAmount");
            if (Convert.ToDouble(txtItemAmount.Text) > Convert.ToDouble(txtTotalAmount.Text))
                args.IsValid = false;
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                //code
            }
        }

uc2.ascx code

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="uc2.ascx.cs" Inherits="DemoCustomValidation.UserControl.uc2" %>
<asp:TextBox ID="txtItemAmount" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomV" runat="server" OnServerValidate="CustomV_Validate"></asp:CustomValidator>

uc2.ascx.cs code

public event ServerValidateEventHandler Customer_ServerValidate;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void CustomV_Validate(object sender, ServerValidateEventArgs e)
        {
            Customer_ServerValidate(sender, e);
        }

 The above example I’ve tested, it can work well. I think it should be what you wat.

Regards

Terry Guo

Hi Terry

Thank you very very much for the solution. Its working perfectly. Smile

[RESOLVED]detailsview validation

I need to do a validaton for a textfield in a detailsview. I have used "custom validator" and want to fire the "server_validate" event. but the "server_validate" event does not fire. I have google for sometime and came to know that it is not possible. However
i need to understand why it is not possible??

Any ideas??[8-)]

 

who said to you that server side validation not fires ?

Check http://forums.asp.net/t/1297601.aspx 

http://forums.asp.net/t/1102008.aspx 

Where did you find that’s not possible? This is normal practice, so it should work!

kamii47

 http://forums.asp.net/t/1102008.aspx 

After seeing the following post only i posted for clarity.

I tried my self by adding a detailsview and a customvalidator and "server_valitdate" function for the custom validator. but the point is the "server_validate" function is never hit.. I would like to know why it was  not possible.??

 

Show an example of the detailsview and the server_validate function?

okay here is code

            <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="Id"
                DataSourceID="SqlDataSource1" Height="50px" Width="125px">
                <Fields>
                    <asp:TemplateField HeaderText="Id" InsertVisible="False" SortExpression="Id">
                        <EditItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text=’<%# Eval("Id") %>’></asp:Label>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text=’<%# Bind("Id") %>’></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name" SortExpression="Name">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text=’<%# Bind("Name") %>’></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
                                EnableClientScript="False" ErrorMessage="*">*</asp:RequiredFieldValidator>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text=’<%# Bind("Name") %>’></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Position" SortExpression="Position">
                        <EditItemTemplate>
                            <asp:TextBox ID="TextBox2" runat="server" Text=’<%# Bind("Position") %>’></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text=’<%# Bind("Position") %>’></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True" />
                </Fields>
            </asp:DetailsView>

  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
             SelectCommand="SELECT * FROM [MovieCategories]"
            UpdateCommand="UPDATE [MovieCategories] SET [Name] = @Name, [Position] = @Position WHERE [Id] = @Id">
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Position" Type="Int32" />
                <asp:Parameter Name="Id" Type="Int32" />
            </UpdateParameters>
             </asp:SqlDataSource>

code behind

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
        {
            TextBox tb = (TextBox)DetailsView1.FindControl("TextBox1");
            if (tb.Text.Length > 0)
            {
                if (args.Value.Length < 1)
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }
    }

Any help???

 

Where is the customvallidator that calls the function? [8-|]

And what exactly is it that you want the validator to do?

Yes From mentioned code we can’t see the custom validator with CustomValidator1_ServerValidate function/event .Is any thing missing in your code ?

kamii47

Yes From mentioned code we can’t see the custom validator with CustomValidator1_ServerValidate function/event .Is any thing missing in your code ?

it is there in the post. but i am giving for reference

 protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
        {
            TextBox tb = (TextBox)DetailsView1.FindControl("TextBox1");
            if (tb.Text.Length > 0)
            {
                if (args.Value.Length < 1)
                {
                    args.IsValid = false;
                }
                else
                {
                    args.IsValid = true;
                }
            }
        }
    }

A, now I understand the problem!

You made a function, but you forgot to put the Custom Validator in the HTML Markup. Just Add:

<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="ErrorMessage" OnServerValidate="CustomValidator1_ServerValidate"  />

Ganesh Jee ,

I can’t see the CustomValidator where CustomValidator1_ServerValidate is binded.

Is there any asp:CustomValidator control with above server validation function is present in your markup ?

 

kamii47

Ganesh Jee ,

I can’t see the CustomValidator where CustomValidator1_ServerValidate is binded.

Is there any asp:CustomValidator control with above server validation function is present in your markup ?

here is the code

<EditItemTemplate>

<asp:TextBox
ID="TextBox1"
runat="server"
Text=’<%# Bind("Name") %>‘></asp:TextBox>&nbsp;

<asp:CustomValidator
ID="CustomValidator1"
runat="server"
ControlToValidate="TextBox1"

ErrorMessage="CustomValidator"
OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

</EditItemTemplate>

Sorry, i might have missed out while pasting the code.

 

Are you sure this is not firing?  Do you have a breakpoint on the first line of your event handler?  Maybe the DetailsView1 is in insert mode and your code is working perfectly.

try to set the OldValuesParameterFormatString Property in the SqlDataSource:

  <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
             SelectCommand="SELECT * FROM [MovieCategories]"
             OldValuesParameterFormatString="{0}"
             UpdateCommand="UPDATE [MovieCategories] SET [Name] = @Name, [Position] = @Position WHERE [Id] = @Id">
            <UpdateParameters>
                <asp:Parameter Name="Name" Type="String" />
                <asp:Parameter Name="Position" Type="Int32" />
                <asp:Parameter Name="Id" Type="Int32" />
            </UpdateParameters>
             </asp:SqlDataSource>

 

Hi Ganesh ,

Try to add ValidateEmptyText="True"

Otherwise , it will not fire the event hanlder when the textbox is empty.

 

Samu Zhang – MSFT

Hi Ganesh ,

Try to add ValidateEmptyText="True"

Yes. it is Server side event is fireing nw.

 

We Are Glad that u have finally solved your problem.

Ganesh Jee Please mark the Post that help you in solving your problem as answer.[not your own post [:D]]

I tried this, but i want to use custom validator in insert mode but still not firing

any suggestions? will it fire inserttemplate?

Yerbol

I tried this, but i want to use custom validator in insert mode but still not firing

any suggestions? will it fire inserttemplate?

 

If you” ve a question. please start your own thread?

http://www.mikesdotnetting.com/Article/69

I was having the same issue with the CustomValidator not firing while a DetailsView was in Insert mode. Some of the responses above helped to to figure out more of what is going on.  Here is what I’ve found: the CustomValidator will only fire after all the
other validator types on the form have fired and validate successfully.

To explain what I mean consider this example:

<asp:GridView ID="gvNews" runat="server" Width="100%" DataSourceID="sqlNews" DataKeyNames="newsId" CellPadding="4" AutoGenerateColumns="false">
  <Columns>
    <asp:CommandField ButtonType="Button" SelectText="View/Edit" ShowSelectButton="true" ItemStyle-Width="75px" />
    <asp:TemplateField HeaderText="Date">
      <ItemStyle Width="160px" />
      <ItemTemplate>
        <asp:Literal ID="gvDate" runat="server" Text=’<%# Eval("newsDate", "{0:MMMM dd, yyyy @ hh:mm tt}") %>’ />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Title">
      <ItemTemplate>
        <asp:Literal ID="gvTitle" runat="server" Text=’<%# Eval("Title") %>’ />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

<div style="margin-top: 12px;">
  <asp:DetailsView ID="dvNews" runat="server" Width="100%" DataSourceID="sqlNewsDetails" DataKeyNames="newsId" CellPadding="6" AutoGenerateRows="false">
    <FieldHeaderStyle Width="100px" />
    <Fields>
      <asp:CommandField ButtonType="Button" EditText="Edit" UpdateText="Save Changes" CancelText="Cancel" ShowEditButton="true" />
      <asp:TemplateField HeaderText="Title*">
        <ItemTemplate>
          <asp:Literal ID="dvTitle" runat="server" Text=’<%# Eval("title_EN") %>’ />
        </ItemTemplate>
        <EditItemTemplate>
          <asp:TextBox ID="txtTitle" runat="server" Width="350px" MaxLength="75" Text=’<%# Bind("title_EN") %>’ />
          <asp:RequiredFieldValidator ID="rfvTitle" runat="server" ControlToValidate="txtTitle" CssClass="errorMessage" Display="Dynamic">What is the Title?</asp:RequiredFieldValidator>
        </EditItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="Video">
        <ItemTemplate>
          <asp:Literal ID="dvVideo" runat="server" Text=’<%# If(String.IsNullOrEmpty(Eval("videoId").ToString), "", String.Format("({0}) {1}", Eval("streamingProviderName"), Eval("videoId"))) %>’ />
        </ItemTemplate>
        <EditItemTemplate>
          <div>
            <asp:DropDownList ID="ddlVideoProvider" runat="server" Width="355px" DataSourceID="sqlVideoProviders" DataTextField="streamingProviderName" DataValueField="providerId" SelectedValue=’<%# Bind("videoProviderId") %>’ AppendDataBoundItems="true">
              <asp:ListItem Text="Select a Streaming Video Provider from the list…" Value="" />
            </asp:DropDownList>
            <asp:CustomValidator ID="cvVideoProvider" runat="server" ControlToValidate="ddlVideoProvider" OnServerValidate="validateVideoProvider" ValidateEmptyText="true" CssClass="errorMessage" Display="Dynamic">If you select a Video Provider, you must enter
a Video ID.</asp:CustomValidator>
          </div>
          <div>
            <asp:TextBox ID="txtVideoId" runat="server" Width="350px" MaxLength="25" Text=’<%# Bind("videoId") %>’ />
            <asp:CustomValidator ID="cvVideoId" runat="server" ControlToValidate="txtVideoId" OnServerValidate="validateVideoId" ValidateEmptyText="true" CssClass="errorMessage" Display="Dynamic">If you enter a Video Id, you must select a Video Provider.</asp:CustomValidator>
          </div>
        </EditItemTemplate>
      </asp:TemplateField>
    </Fields>
  </asp:DetailsView>
</div>

<asp:SqlDataSource ID="sqlNews" runat="server" ConnectionString="<%$ ConnectionStrings: ConnString %>"

SelectCommand="SELECT newsId, Title_EN AS Title, newsDate FROM cms_News ORDER BY newsDate DESC" SelectCommandType="Text">
</asp:SqlDataSource>

<asp:SqlDataSource ID="sqlNewsDetails" runat="server" ConnectionString="<%$ ConnectionStrings: ConnString %>"

SelectCommand="SELECT newsId, title_EN, videoId, videoProviderId, streamingProviderName FROM cms_News n LEFT JOIN cms_VideoProviders vp ON n.videoProviderId=vp.providerId WHERE newsId=@newsId" SelectCommandType="Text"
UpdateCommand="UPDATE cms_News SET title_EN=@title_EN, videoId=@videoId, videoProviderId=@videoProviderId WHERE newsId=@newsId" UpdateCommandType="Text">
<SelectParameters>
  <asp:ControlParameter Name="newsId" Type="Int32" ControlID="gvNews" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>

<asp:SqlDataSource ID="sqlVideoProviders" runat="server" ConnectionString="<%$ ConnectionStrings: ConnString %>"
SelectCommand="SELECT providerId, streamingProviderName FROM cms_VideoProviders ORDER BY streamingProviderName" SelectCommandType="Text">
</asp:SqlDataSource>

This is a fully functioning demo. All you need to do is create a database with the two tables showing in the SqlDataSource statements. The idea is the GridView shows all of the news items. Each news item can have an embedded video associated with it. In
order to provide flexibility on the embedded videos, the VideoProvider table defines all the available video providers. The CustomValidators make sure that if a Video Provider is selected then a VideoId is entered and visa versa.

Notice how the Title field is marked as a required field and has a RequiredFieldValidator attached to it. If the Title field has an entry in it (and therefore the RequiredFieldValidator is successful) then, and only then will the CustomValidators fire and
make sure the the Video stuff is all there if an entry is made in one or the other field. If the Title field is empty, then only the RequiredFieldValidator will fire and none of the error messages for the DropDownList or the TextBox will fire.

This holds true for Edit mode or Insert mode.

I hope this helps others understand a bit better what is happening and when to expect the CustomValidators to fire.

rweiler

I was having the same issue

And did read my previous answer?

[RESOLVED]Set AJAX CalendarExtender with JavaScript

I have two CalendarExtenders on a simple web form.  When txtStartDt is clicked on, JavaScript runs to dynamically set the StartDate of the txtStartDt_CalendarExtender to the current date (which makes every date before today invalid).  When a date is selected,
another JavaScript function runs to set the end date of the txtEndDt_CalendarExtender so that a user can’t select a date range longer than 30 days.

The scripts run great.  The problem is that when the a new date is selected selected on the StartDt, the txtEndDt_CalendarExtender doesn’t reset until a date is selected there.  When I step though the code, it shows that the EndDt has been changed, but it’s
not rendering on the control.

 

<asp:TextBox ID="txtStartDt" runat="server" CssClass="txtDt"></asp:TextBox>

<aspA:CalendarExtender ID="txtStartDt_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtStartDt" OnClientShowing="setStartDate" OnClientDateSelectionChanged="setEndDate"></aspA:CalendarExtender>


<asp:TextBox ID="txtEndDt" runat="server" CssClass="txtDt"></asp:TextBox>

<aspA:CalendarExtender ID="txtEndDt_CalendarExtender" runat="server" Enabled="True" TargetControlID="txtEndDt">
</aspA:CalendarExtender>


function setStartDate(sender, args) {
    sender._startDate = new Date();
}

function setEndDate(sender, args) {
     var stdt = new Date(document.getElementById("txtStartDt").value)
    var eddt = document.getElementById("txtEndDt")
    var s1 = new Date()

    s1.setDate(stdt.getDate() + 30);

    eddt.CalendarBehavior.initialize;
    eddt.CalendarBehavior.set_endDate(s1);
}

 

I’ve tried initializing the extendar, but nothing seems to reset it from a user perspective until a date is selected.

Hi,

Please refer to the code as follow:

<title></title>

    <script type="text/javascript">
        function test() {
            $find("CalendarExtender1")._textbox.set_Value(new Date().format($find("CalendarExtender1")._format));
        }
        function checkDate(sender, args) {
            if (sender._selectedDate < new Date()) {
                alert("You cannot select a day earlier than today!");
                sender._selectedDate = new Date();
                // set the date back to the current date
                sender._textbox.set_Value(sender._selectedDate.format(sender._format))
            }
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Date" OnClientClick="test()" />
    <asp:CalendarExtender ID="CalendarExtender1" BehaviorID="CalendarExtender1" runat="server" TargetControlID="TextBox1" PopupButtonID="Button1"
        OnClientDateSelectionChanged="checkDate">
    </asp:CalendarExtender>
    </form>

That works, but I’m trying to reset the available values on the Calendar Extender without having someone select a date on it.  My issue is that I have 2 Extenders.  When someone changes the date on the first one, I need the second one to update without someone
selecting a date on it.  Right now, you have to click a date on the second one for it to update the second time.

This doesn’t seem to be a hot topic, so I went another route.  I decided to use a Customer Validator with some JavaScript to confirm that the date is within 30 days.  I’ve included the code below in case it helps someone else.

 

<asp:CustomValidator ID="compareDates30" runat="server" ErrorMessage="Date Range has to be less than 30 days"
                            ClientValidationFunction="checkDate30" CssClass="Validation">*</asp:CustomValidator>


function checkDate30(sender, args) {
    var sd = $get("txtStartDt").value
    var ed = $get("txtEndDt").value
    var s1 = new Date(sd)
    var e1 = new Date(ed)

    s1.setDate(s1.getDate() + 30)

    if (e1 > s1) {
        args.IsValid = false
    }
    else {
        args.IsValid = true
    }

ValidatorEnable Javascript Function

Hi,

 I am calling the ValidatorEnable function in Javascript to disable or enable validators on the client side based on whether or not a checkbox is checked. The problem I am encountering is that, when I re-enable the required field validators, the validation
errors show up right away because the fields are empty. I do not want this. I only want the validation error to show once the form is submitted. How can I do this?

 Thx.

 

Hi!

Do you want these validations to occur with postback or without post back…..after clicking on the submit button

 

 

We might be able to help better if you post the code so we could see exactly what you are doing.

NC…

 

I’m having the same problem.  When I enable a validator using javascript:ValidatorEnable, the validation fires immediately, rather than when the page is submitted.  I have a checkbox that enables the validator client-side.  The critical part of the onclick
function looks like:

oVal = document.getElementById("<%=rfvUserNameRequired.ClientID %>");

ValidatorEnable(oVal, true);

 

Thanks for any help!

Wieland

 

I found this post while trying to solve the same problem myself and worked it out and thought I’d share the solution.

When you call ValidatorEnable(val, enable) it calls a function that looks like this: 

function ValidatorEnable(val, enable)
{
     val.enabled = (enable != false);
     ValidatorValidate(val);
     ValidatorUpdateIsValid();
}
By just enabling/disabling the validator (see line 3) you can achieve the same result as calling ValidatorEnable.
Taking it one step further, if you want to update the display just call ValidatorUpdateDisplay(val) straight afterwards. This is done in ValidatorValidate(val) after it validates (as in line 4).
So to solve your problem do this: 
 
oVal = document.getElementById("<%=rfvUserNameRequired.ClientID %>");
oVal.enabled = true;
ValidatorUpdateDisplay(val);
I hope this helps you or anyone else with the same problem.

I have tried the suggestion outlined  here but get an object does not support this property or method on line 2...when typing the code intellisense does not pick up the enabled property
 
1    oVal = document.getElementById("<%=rfvUserNameRequired.ClientID %>");
2    oVal.enabled(true);
3    ValidatorUpdateDisplay(val);
 
Here is my code:
function ResponseMethodChanged()

{

var validator = document.getElementById('valName');

var validator = document.getElementById('valName'); // I have also tried using the <%=valName.ClientID%> syntax as well...no luck

validator.enabled(true); //Error occurs here

}

 

Any suggestions? I am using VS 2008/asp.net 3.5/IE 7, Win XP Pro SP2

 

Thank you

 

Sorry about that, seems like there was a typo in my post. You still need to use the <%=valName.ClientID%> to get the generated page id of the validator. But where you get the error, try using validator.enabled = true;

 I will update my original post in this regard.

hi,

   me also facing same problem ,can u explain it detaily and give me that code also

Hey Senthilkumar,

To enable a validator without it actually validating its expression all you need to do is:

var validator = $get('<%=validator.ClientID %>');


validator.enable = true;
ValidatorUpdateDisplay(validator);

That should do the trick. Let me know if you have any problems.

hi TwiggzSA

i tried that above code validator.enable shows undefined

Did you change the ‘<%=validator.ClientID %>’ to your validators ID. I.e. ‘<%=[your validator ID].ClientID %>’

Check if validator is undefined or if enable is undefined. If validator is undefined then you need to either change as I mentioned above or you could try to use:

document.getElementById(‘<%=[your validator ID].ClientID %>’);

instead of:

$get(‘<%=[your validator ID].ClientID %>’);

Let me know if that helps.

What it does is:

  1. Use a customValidator (not a RequiredFieldValidator) control that validates the textbox using a javascript function called Validator.
  2. The validator function checks if the checkbox is checked and validates the textbox. if the checkbox is not checked , without checking the value of the textbox, the validator function returns true by setting e.IsValid = true;

Use this javascript:

function Validator(sender, e){
    var chkValidate = document.getElementById("chk");
    var txtName = document.getElementById(sender.controltovalidate);
    e.IsValid = true;
    if(chkValidate.checked)
        if(txtName == null || txtName.value.length == 0)
            e.IsValid = false;
    }

use these controls:

<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator2" runat="server" 
    ErrorMessage="CustomValidator" ClientValidationFunction="Validator" 
    ControlToValidate="txtEmployeeName" ValidateEmptyText="True"></asp:CustomValidator>
<asp:CheckBox ID="chk" runat="server" 
    Text="Validate employee name" />
<asp:Button ID="btnValidator" runat="server" Text="Button" />

 

I tried the following and it worked.. hope it helps someone

ValidatorEnable(id, true);
id.isvalid = true;
ValidatorUpdateDisplay(id);

Why don’t you answer new posts and not ones that are 6 months old?

NC…

 

Because he can. He added new, meaningful value and context – nothing wrong with that. By the way, it wasn’t even 6 months. I don’t understand why people get dissed when they (sometimes accidentally) dare to reply to an open thread.

Thanks TwiggzSA

This worked for me…

I know it is not popular to post on older threads, but there are some errors I found in the provided code and wanted to share what needs to be done so it works correctly.

1st off calling either ‘ValidatorEnable’ or ‘ValidatorUpdateDisplay’ will immediately validate the associated control and show any validation messages. If this is not wanted because you just want to toggle the enabled/disabled switch but wait until form
submission to validate, then the 2nd method of calling enabled on the object is the preferred method. If you
do want immediate validation, then this can be done in a single line of code passing in the ID of the RequiredFieldValidator as displayed below:

ValidatorEnable($get('<%=RequiredFieldValidator1.ClientID %>'), true);

However, if you want only to enable/disable the validator, use the code below and do not make any additional calls to the built in JS functions. The error from previous posts states to set the .enable property yet there is no such thing. You must set the .enabled property on the server control. The code below shows this:

var validator = $get('<%=RequiredFieldValidator1.ClientID %>');
validator.enabled = true;

Note, the above code using the get$ method. I found it to be the easiest way to get the control’s instance or the JS would error stating ‘style’ is not defined on the following line within the ValidatorUpdateDisplay() function: val.style.visibility = val.isvalid
? "hidden" : "visible";

[RESOLVED]Validator Callout Extender and HTML Editor Extender does not fire next to textbox

Hi All, I’m using the HTMLEditorExtender and ValidatorCalloutExtender.  The ValidatorCalloutExtender works well with regular text boxes, but when I try to use it with the HTMLEditorExtender it pops up at the top of the page.  I’m using custom CSS and I’m
able to do everthing accept move it down to the HTMLEditorExtender box.

Here is my code:

<div class="subtitle" align="center">
      Description <br /><br />
                                                    
        <asp:TextBox ID="txtDescription" Width="400px" Height="200px" CssClass="form-td" runat="server"
                                                   TextMode="SingleLine" />
        <asp:RequiredFieldValidator ID="rfvDescription" runat="server" ErrorMessage="Description is Required"
                                                   CssClass="error" Font-Bold="True" Font-Size="10pt" ControlToValidate="txtDescription"
                                                   Display="None" EnableViewState="False"></asp:RequiredFieldValidator>
        <asp:ValidatorCalloutExtender ID="VCE4" runat="server" CssClass="CustomValidator3"
                                                   CloseImageUrl="images/close.png" TargetControlID="rfvDescription" />
        <asp:HtmlEditorExtender ID="HTMLEditorExtender" runat="server"
                                                    TargetControlID="txtDescription" EnableSanitization="False">
                                                    <toolbar>
                                                    <asp:Undo />
                                                    <asp:Redo />
                                                    <asp:Bold />
                                                    <asp:Italic />
                                                    <asp:Underline />
                                                    <asp:StrikeThrough />
                                                    <asp:Subscript />
                                                    <asp:Superscript />
                                                    <asp:JustifyLeft />
                                                    <asp:JustifyCenter />
                                                    <asp:JustifyRight />
                                                    <asp:JustifyFull />
                                                    <asp:InsertOrderedList />
                                                    <asp:InsertUnorderedList />
                                                    <asp:CreateLink />
                                                    <asp:UnLink />
                                                    <asp:RemoveFormat />
                                                    <asp:SelectAll />
                                                    <asp:UnSelect />
                                                    <asp:Delete />
                                                    <asp:Cut />
                                                    <asp:Copy />
                                                    <asp:Paste />
                                                    <asp:BackgroundColorSelector />
                                                    <asp:ForeColorSelector />
                                                    <asp:FontNameSelector />
                                                    <asp:FontSizeSelector />
                                                    <asp:Indent />
                                                    <asp:Outdent />
                                                    <asp:InsertImage />
                                                    <asp:InsertHorizontalRule />
                                                    <asp:HorizontalSeparator />
                                                    </toolbar>
                                                </asp:HtmlEditorExtender>
                                           </div>

CSS:

.CustomValidator3 {
       margin-left:-3px; width:250px; margin:50px;
    }  
.CustomValidator3 div {
    border:solid 1px Black; background-color:#ffffff;  
                              }  
.CustomValidator3 td {
    border:solid 1px Black; background-color:#ffffff;
    }  
.CustomValidator3 .ajax__validatorcallout_popup_table {
    display:none; border:none; background-color:transparent; padding:5px;
    }  
.CustomValidator3 .ajax__validatorcallout_popup_table_row {
    vertical-align:top; height:50px; background-color:transparent; padding:50px;
    }  
.CustomValidator3 .ajax__validatorcallout_callout_cell {
    width:20px; height:50px; text-align:left; vertical-align:top; border:none; background-color:transparent; padding:0px;
    }  
 .CustomValidator3 .ajax__validatorcallout_callout_table {
    height:50px; border:none; background-color:transparent; padding:0px;
    }  
 .CustomValidator3 .ajax__validatorcallout_callout_table_row {
    background-color:transparent; padding:0px;
    }
 .CustomValidator3 .ajax__validatorcallout_callout_arrow_cell {
    padding:8px 0px 0px 0px; text-align:left; vertical-align:top; font-size:1px; border:none; background-color:transparent;
    }  
 .CustomValidator3 .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv {
    font-size:5px; position:relative; left:1px; border-bottom:none; border-right:none; border-left:none;
    width:15px; background-color:transparent; padding:0px;
    }  
 .CustomValidator3 .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv div {
    height:1px; overflow:hidden; border-top:none; border-bottom:none; border-right:none; padding:0px; margin-left:auto;
    }  
 .CustomValidator3 .ajax__validatorcallout_error_message_cell {
    font-family:Verdana; font-size:10px; color:#333333; padding:10px; border-right:none; border-left:none; 
    }  
 .CustomValidator3 .ajax__validatorcallout_icon_cell {
    width:20px; padding:5px; border-right:none;
    }  
 .CustomValidator3 .ajax__validatorcallout_close_button_cell {
    vertical-align:top; padding:3px; text-align:left; border-left:none;
    }  
 .CustomValidator3 .ajax__validatorcallout_close_button_cell .ajax__validatorcallout_innerdiv {
    border:none; text-align:left; width:10px; padding:2px; cursor:pointer;
    }  

Hello

If you are in Chrome, you can try debug the CSS by pressing F12. When the popup comes up, see what CSS properties are applied to it. You can consider position:absolute; to make the popup stay at a particular part in the page.

[RESOLVED]Custumvalidator not firing on submit

Hi All

I have customvalidator to check for the duplicate names from DB which is done using Jquery ,which fires on Onblur of the textbox,

When hit the submit button even if call for the jquery is done the validation is not firing

Code:

function ValidateDuplicatename(sender, args)
        {
            var jsonParam = ‘{"Productname": "’ + document.getElementById(‘<%=txtprdname.ClientID %>’).value + ‘"}’;
            $.ajax
            (
                {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: jsonParam,
                    dataType: "json",
                    url: ‘ControlPanel.aspx/CheckForDuplicateProductleadName’,
                    success: function(msg)
                    {
                        document.getElementById(‘<%=hfIsPresentProductlead.ClientID %>’).value = msg.d.toString().toLowerCase().trim()
                    }
                }
            );
                if (document.getElementById(‘<%=hfIsPresentProductlead.ClientID %>’).value == "true") {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
            }
        }

Code behind

<WebMethod()> _
Public Shared Function CheckForDuplicateProductleadName(ByVal Productname As String) As String
…………….. Some code………………
        If _ProductleadCount > 0 Then
            Return "true"
        Else
            Return "false"
        End If

Please any pointer is also is a great relief …

    End Function
End Class

Add an event handler for error so you can check the xhr status code. Also, ruyn a network trace to see what is (or is not) being sent on the network.
Fiddler is one of the best tools for this.