顯示具有 CustomValidator 標籤的文章。 顯示所有文章
顯示具有 CustomValidator 標籤的文章。 顯示所有文章

2014年7月13日 星期日

[RESOLVED] Is it possible to validate 2 controls with 1 validator


Say, I actually want 1 required field validator and 2 radiolist controls.and i have a selection option there where i want either radiolist1 or radiolist2 to be validated not selecting neither radio1 or radio2 will give error.Is it Possible?


If this is not possible then I have to use a textbox to validate all these..



i think not possible that is what i need to say as is. reason the control id is one that bind with a validator control. yes contrary to is radolist


validation in this could be off comparevalidator.









Hi anirudh_4sag,


I think for such validation which are not possible to be implemented directly by built-in server controls, you should use CustomValidator. and in server side Validate event of this Validator, you can write custom code to put your custom validation code.



Hi,


One suggestion is you can change the controltovalidate attribute of validator on code behind based on the situation.


eg:


if(conditon)


{


validator1.controltovalidate=ID of control1;


}


else


{


validator1.controltovalidate=ID of control2;


}


Thanks,


Saritha.



The built in validator controls (such as RequiredField etc) all act on a single control (apart from the Comapre one, obviously).  If you need validator controls that act on multiple controls based on custom logic then you have to use a custom validator. 
Google for the exact syntax but it's quite straight-forward.  You just specify the method you want to use when the control is asked to validate, you do your work and specify true or false for if the validation worked.  If you want to support client-side validation
there is similarly a property that lets you specify the name of a javascript function to call.


[RESOLVED] Is it possible to validate 2 controls with 1 validator


Say, I actually want 1 required field validator and 2 radiolist controls.and i have a selection option there where i want either radiolist1 or radiolist2 to be validated not selecting neither radio1 or radio2 will give error.Is it Possible?


If this is not possible then I have to use a textbox to validate all these..



i think not possible that is what i need to say as is. reason the control id is one that bind with a validator control. yes contrary to is radolist


validation in this could be off comparevalidator.









Hi anirudh_4sag,


I think for such validation which are not possible to be implemented directly by built-in server controls, you should use CustomValidator. and in server side Validate event of this Validator, you can write custom code to put your custom validation code.



Hi,


One suggestion is you can change the controltovalidate attribute of validator on code behind based on the situation.


eg:


if(conditon)


{


validator1.controltovalidate=ID of control1;


}


else


{


validator1.controltovalidate=ID of control2;


}


Thanks,


Saritha.



The built in validator controls (such as RequiredField etc) all act on a single control (apart from the Comapre one, obviously).  If you need validator controls that act on multiple controls based on custom logic then you have to use a custom validator. 
Google for the exact syntax but it's quite straight-forward.  You just specify the method you want to use when the control is asked to validate, you do your work and specify true or false for if the validation worked.  If you want to support client-side validation
there is similarly a property that lets you specify the name of a javascript function to call.


[RESOLVED] Is it possible to validate 2 controls with 1 validator


Say, I actually want 1 required field validator and 2 radiolist controls.and i have a selection option there where i want either radiolist1 or radiolist2 to be validated not selecting neither radio1 or radio2 will give error.Is it Possible?


If this is not possible then I have to use a textbox to validate all these..



i think not possible that is what i need to say as is. reason the control id is one that bind with a validator control. yes contrary to is radolist


validation in this could be off comparevalidator.









Hi anirudh_4sag,


I think for such validation which are not possible to be implemented directly by built-in server controls, you should use CustomValidator. and in server side Validate event of this Validator, you can write custom code to put your custom validation code.



Hi,


One suggestion is you can change the controltovalidate attribute of validator on code behind based on the situation.


eg:


if(conditon)


{


validator1.controltovalidate=ID of control1;


}


else


{


validator1.controltovalidate=ID of control2;


}


Thanks,


Saritha.



The built in validator controls (such as RequiredField etc) all act on a single control (apart from the Comapre one, obviously).  If you need validator controls that act on multiple controls based on custom logic then you have to use a custom validator. 
Google for the exact syntax but it's quite straight-forward.  You just specify the method you want to use when the control is asked to validate, you do your work and specify true or false for if the validation worked.  If you want to support client-side validation
there is similarly a property that lets you specify the name of a javascript function to call.


[RESOLVED] Is it possible to validate 2 controls with 1 validator


Say, I actually want 1 required field validator and 2 radiolist controls.and i have a selection option there where i want either radiolist1 or radiolist2 to be validated not selecting neither radio1 or radio2 will give error.Is it Possible?


If this is not possible then I have to use a textbox to validate all these..



i think not possible that is what i need to say as is. reason the control id is one that bind with a validator control. yes contrary to is radolist


validation in this could be off comparevalidator.









Hi anirudh_4sag,


I think for such validation which are not possible to be implemented directly by built-in server controls, you should use CustomValidator. and in server side Validate event of this Validator, you can write custom code to put your custom validation code.



Hi,


One suggestion is you can change the controltovalidate attribute of validator on code behind based on the situation.


eg:


if(conditon)


{


validator1.controltovalidate=ID of control1;


}


else


{


validator1.controltovalidate=ID of control2;


}


Thanks,


Saritha.



The built in validator controls (such as RequiredField etc) all act on a single control (apart from the Comapre one, obviously).  If you need validator controls that act on multiple controls based on custom logic then you have to use a custom validator. 
Google for the exact syntax but it's quite straight-forward.  You just specify the method you want to use when the control is asked to validate, you do your work and specify true or false for if the validation worked.  If you want to support client-side validation
there is similarly a property that lets you specify the name of a javascript function to call.


[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" %>




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

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




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


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


           
                DataSourceID="SqlDataSource1" Height="50px" Width="125px">

               

                   

                       

                           

                       


                       

                           

                       


                   


                   

                       

                           

                           
                                EnableClientScript="False" ErrorMessage="*">*


                       


                       

                           

                       


                   


                   

                       

                           

                       


                       

                           

                       


                   


                   

               


           


 
             SelectCommand="SELECT * FROM [MovieCategories]"

            UpdateCommand="UPDATE [MovieCategories] SET [Name] = @Name, [Position] = @Position WHERE [Id] = @Id">

           

               

               

               

           


            


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:




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> 



<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:


 
             SelectCommand="SELECT * FROM [MovieCategories]"

             OldValuesParameterFormatString="{0}"

             UpdateCommand="UPDATE [MovieCategories] SET [Name] = @Name, [Position] = @Position WHERE [Id] = @Id">

           

               

               

               

           


            


 



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:




 

   

   

     

     

       

     


   


   

     

       

     


   


 





 

   

   

     

     

       

         

       


       

         

          What is the Title?

       


     


     

       

         

       


       

         


           

             

           


            If you select a Video Provider, you must enter
a Video ID.


         


         


           

            If you enter a Video Id, you must select a Video Provider.

         


       


     


   


 





SelectCommand="SELECT newsId, Title_EN AS Title, newsDate FROM cms_News ORDER BY newsDate DESC" SelectCommandType="Text">







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



 





SelectCommand="SELECT providerId, streamingProviderName FROM cms_VideoProviders ORDER BY streamingProviderName" SelectCommandType="Text">


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?