Link to home
Start Free TrialLog in
Avatar of cdfllc
cdfllc

asked on

RequiredFieldValidator on dropdownlist

I have a RequiredFieldValidator on a dropdownlist, and when I initially populate the list and submit the form, without changing the values it doesn't prompt me with the validation message, however, after the postback, if I try and submit the page again, without changing the dropdownlist - it does show me the validation message!!

Help, how do I begin debugging this?  Where is it going wrong?

thanks!!

cdfllc
Avatar of surajguptha
surajguptha
Flag of United States of America image

RequiredFieldValidator has a initialValue property against which you can set the default value. Set it to the value that is populated in the dropdown by default.

I hope i have understood ur question if not please correct me
SOLUTION
Avatar of puranik_p
puranik_p
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cdfllc
cdfllc

ASKER

I am getting the same behavior when I add that dropdownlist as well !! That is weird, I didn't expect that!

My "save" button calls "javascript:__doPostBack('DefaultHeader$DataActionBar$SaveButton','')"

And my initial value is "", and when I view source of the created page, the value of the list item is the same - ""
Just as in the example above by puranik_p
<option value="">Please select one</option>

Mine says:
<option value="">-- Select User --</option>

I have tried putting alerts in the WebUIValidation.js, but they never show... I don't know how else to go about debugging...
Avatar of cdfllc

ASKER

Here is what my source looks like when the page loads (when I hit "New"):

<select name="DetailControl:ddlUserList:UserList" onchange="__doPostBack('DetailControl$ddlUserList$UserList','')" language="javascript" id="DetailControl_ddlUserList_UserList" savetype="NVarChar" dbFieldName="manager" ddlId="ddlUserList">
      <option selected="selected" value="">-- Select User --</option>
      <option value="F79E0208-74F0-460E-AF51-C67A4BCE6F65">yyy</option>
      <option value="71D0E5A6-AE9E-4F25-83F5-39CD2ACBE6EA">xxx</option>

</select><span id="DetailControl_ddlUserList_reqVal" controltovalidate="DetailControl_ddlUserList_UserList" evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color:Red;visibility:hidden;">(required)</span>
Try giving the "Please select one" as the initial value instead of "". I am not sure if it will work but give it a try :)
I have checked it. Please assign the initialValue attribute to the "Message" in the text part and not the value.
The initialValues specified is validated against the Text and not the Value

Hope this helps
Avatar of cdfllc

ASKER

Ok, I changed the initialvalue="-- Select User --", see below...
But now, I don't get any validation hapenning at all!! -- not even on the second time I hit save, like it used to...


<select name="DealDetailControl:ddlUserList:UserList" onchange="__doPostBack('DealDetailControl$ddlUserList$UserList','')" language="javascript" id="DealDetailControl_ddlUserList_UserList" savetype="NVarChar" dbFieldName="deal_manager" ddlId="ddlUserList">
      <option value="">-- Select User --</option>
      <option selected="selected" value="F79E0208-74F0-460E-AF51-C67A4BCE6F65">bthews</option>
      <option value="71D0E5A6-AE9E-4F25-83F5-39CD2ACBE6EA">xxx</option>

</select><span id="DealDetailControl_ddlUserList_reqVal" controltovalidate="DealDetailControl_ddlUserList_UserList" evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="-- Select User --" style="color:Red;visibility:hidden;">(required)</span>
Try using a ASP:DropDownList instead of the Select option
If u have used a ASP:DropDownList and the code posted is the rendered code check if the AUTOPOSTBACK is set to false (i might be wrong here)
It works perfectly for me. All i did is

1) Added a ASP:DropDownList
2) Added the collections with the default selected item with value "" and text "Select an Option"
3) Dragged a RequiredFieldValidator
4) Set the Control to validate to the DropDownList
5) Set the Initial Value as "Select an Option"
6) Voila it worked for me

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cdfllc

ASKER

Sorry for the confusion, the <SELECT...> that I have been posting is the "generated" HTML code. I am using this dropdownlist:

<asp:dropdownlist id="UserList" runat="Server" AutoPostBack="True"></asp:dropdownlist><asp:requiredfieldvalidator id="reqVal" Runat="Server" Text="(required)" InitialValue="" ControlToValidate="UserList"></asp:requiredfieldvalidator>

Do I have to use AutoPostBack = "false" ?

thanks,
cdfllc
b1xml2,
              Kindly check what initialValue points to. Because a initialValue is not always validating dropdowns, it also validates textboxes and may be thats why it is called "Value" . I checked it myself by coding a small program. It looks like it validates against the TEXT displayed and not the value part in the collection. Kindly check it and let me know. :)

cdfllc ,
             Yes Set AutoPostBack as false. My GUESS is that it is the one that is causing the problem. Let me know if it works.

Regards,
Suraj
it validates against the Value in the DropDownList and the Value in the TextBox
it does not validate against the Text in the DropDownList.
suraj whatever you are on, get off it. RequiredFieldValidators validate against the VALUE and not the TEXT portion of DropDownLists... This has been the way since ASP.NET 1.0.


b1xml2 ,
             I have a code besides me that works that way. I dont know why. Can you kindly check it against some quick coding please. I am not very sure about it but the code i have done makes me think i am correct. Please try it out and let me know.

Thanks,
Suraj
ASP.NET [c#]
==========
<%@ Page language="c#"%>
<script language="C#" runat="server">
void btnSave_Click(object sender,EventArgs e)
{
      if (Page.IsValid)
      {
            Response.Write("Saving...");
      }
}
</script>
<html>
<head>
<title>RequiredValidatorsExample</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:DropDownList ID="ddlCountries" Runat="server">
<asp:ListItem Value="-1">Please Select</asp:ListItem>
<asp:ListItem Value="US">United States</asp:ListItem>
<asp:ListItem Value="UK">United Kingdom</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvCountries" Runat="server" ErrorMessage="Required" ControlToValidate="ddlCountries" InitialValue="-1" /><br />
<asp:LinkButton ID="btnSave" Runat="server" CausesValidation="True" OnClick="btnSave_Click">Save</asp:LinkButton>
</form>
</body>
</html>


ASP.NET [VB]
========
<%@ Page language="VB%>
<script language="VB" runat="server">
Sub btnSave_Click(ByVal sender As Object,e As Object)
      If Page.IsValid Then
            Response.Write("Saving..")
      End If
End Sub
</script>
<html>
<head>
<title>RequiredValidatorsExample</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:DropDownList ID="ddlCountries" Runat="server">
<asp:ListItem Value="-1">Please Select</asp:ListItem>
<asp:ListItem Value="US">United States</asp:ListItem>
<asp:ListItem Value="UK">United Kingdom</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvCountries" Runat="server" ErrorMessage="Required" ControlToValidate="ddlCountries" InitialValue="-1" /><br />
<asp:LinkButton ID="btnSave" Runat="server" CausesValidation="True" OnClick="btnSave_Click">Save</asp:LinkButton>
</form>
</body>
</html>
The code posted above shows without doubt that the InitialValue of the RequiredFieldValidator checks against the SelectedValue in the DropDownList and not any Text. As you can see the InitialValue is "-1" and NOT "Please select". Clicking on the save button when the first item is selected causes the RequiredFieldValidator to display the error message.

Suraj is vert much mistaken about the RequiredFieldValidator validating against the Text of the DropDownList. As they say, a little knowledge is dangerous.
<asp:DropDownList id="DropDownList1" style="Z-INDEX: 101; LEFT: 408px; POSITION: absolute; TOP: 128px"
                        runat="server">
<asp:ListItem Value="a">a</asp:ListItem>
<asp:ListItem Value="b">b</asp:ListItem>
<asp:ListItem Selected="True">Please</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" style="Z-INDEX: 102; LEFT: 304px; POSITION: absolute; TOP: 264px" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="DropDownList1" InitialValue="Please"></asp:RequiredFieldValidator>

Well above is the code that worked for me. I would be more than happy to learn from a experienced person like you :)
as i said, a little knowledge is dangerous:

<asp:ListItem Selected="True">Please</asp:ListItem> is the same as <asp:ListItem Value="Please" Selected="True">Please</asp:ListItem> and so the validator checks against the value of the DropDownList which in this case is "Please"

now, change to
<asp:ListItem Value="-1" Selected="True">Please</asp:Item> and tell me what happens hmmmmmmmmmmmmmmmmmmm!!!!

You must be very careful is trying to provide "expert" advice if you are not sure.
b1xml2 ,
             Thanks. It did work :). But note that it did read the Text part when the value was not available. So i am not completely wrong anyways :P

I am a Master in ASP .net too. So kindly dont use strong words. Everyone is learning here.

Regards,
Suraj Guptha

errata in VB example too quick in typing
=============
<script language="VB" runat="server">
Sub btnSave_Click(ByVal sender As Object,ByVal e As EventArgs)
     If Page.IsValid Then
          Response.Write("Saving..")
     End If
End Sub
</script>
Sorry, but you are 100% ABSOLUTELY MISTAKEN then. You are not even close.

The InitialValue NEVER EVER validates against the Text of the DropDownList. That's a fact. Certification here has nothing to do with facts. You maintained a false stance despite being told otherwise. As I said, a little knowledge is dangerous.
b1xml2,
              U were Right, I was wrong. Thanks for letting me know what is right.

cdfllc ,
            Try setting the AutoPostBack to false and let me know if it works or not.

Regards,
Suraj Guptha
Avatar of cdfllc

ASKER

Well, that was very entertaining guys ;)

Anyways, no setting the AutoPostaBack="False" did not work.
Do you guys know how to tell what is going on? i.e. run this through some sort of debugger, or put some print out statements in the code?

thanks,
cdfllc
*bows*
use the code i have shown as an example....

1. find out what is the value you do not consider as valid in the DropDownList, and set that in the InitialValue attribute of the RequiredFieldValidator
2. Use a LinkButton and set the CausesValidation to True, It will trigger off client-side validation.
3. On the server-side where you are expecting to process the page, use Page.IsValid checks first.
4. Turn off AutoPostBack and see how the validation flows.
5. Turn it back on and see the impact on the validator.

MS's validation framework in ASP.NET is still pretty rudimentary.
Avatar of cdfllc

ASKER

Maybe this information will give you a clue:

I create a new, which loads in the dropdownlist.
If I choose a user from the list, and then switch back to "-- Select a user --" - it shows the (required) label in red - like we'd expect.
However, it still lets me submit the form!!

Now when the page comes back, from that post back, and I try and save again - without selecting a user, now it prevents me from saving!!
Why have u turned AutoPostBack to true ? What is need for it functionally ?

Do you click a button after selecting the user from the dropdown??Or the post back you are referring to is the one caused by the dropdown item change itself?

Kindly let us know the answers of the above two questions
Avatar of cdfllc

ASKER

I have now turned off AutoPostBack.
AutoPostBack="False"

Yes, I am clicking an asp:hyperlink whose URL = "javascript:__doPostBack('DefaultHeader$DataActionBar$SaveButton','')";

This causes a post back. That is my "Save" "button"

cdfllc
1) Can you try changing the asp:hyperlink to an asp:button ? and make sure autopostback = false is set for the dropdown

2) Please let us know why you set AutoPostBack = True.

3) Post the codebehind of all the three controls that u are using. The DropDown, Vaidator and the Hyperlink that causes the postback. Provide the codebehind code and not the rendered code
Avatar of cdfllc

ASKER

The .apsx page has a user control with my drop down:

<%@ Register TagPrefix="it" TagName="DDLUserList" Src="~/Web/UserControls/DDLUserList.ascx" %>
<it:DDLUserList id="ddlUserList" ddlId="ddlUserList" savetype="NVarChar" dbfieldname="deal_manager"
                                          DisplayDefault="true" Required="true" Runat="Server" />

DDLUserList.ascx:
<%@ Control Language="c#" AutoEventWireup="false" Codebehind="DDLUserList.ascx.cs" Inherits="cdrm2.Web.UserControls.DDLUserList" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<asp:dropdownlist id="UserList" runat="Server" AutoPostBack="False"></asp:dropdownlist><asp:requiredfieldvalidator id="reqVal" Runat="Server" Text="(required)" InitialValue="" ControlToValidate="UserList"></asp:requiredfieldvalidator>


DDLUserList.ascx.cs:
namespace cdrm2.Web.UserControls
{
      using System;
      using System.Collections;
      using System.Data;
      using System.Drawing;
      using System.Web;
      using System.Web.UI.WebControls;
      using System.Web.UI.HtmlControls;
      using cdrm2.Business.User;
      using cdrm2.Configuration;

      /// <summary>
      ///            Summary description for DDLUserList.
      /// </summary>
      public class DDLUserList : System.Web.UI.UserControl
      {
            protected System.Web.UI.WebControls.DropDownList UserList;
            private ITUserCollection datasource;
            private string dataText = "";
            private string dataValue = "";
            private string savetype = "";
            private string ddlId = "";
            protected System.Web.UI.WebControls.RequiredFieldValidator reqVal;
            protected System.Web.UI.WebControls.DropDownList DropDownList1;
            protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
            private string dbFieldName = "";

            private void Page_Load(object sender, System.EventArgs e)
            {
                  if (GlobalConfigurations.ConfirmChanges)
                  {                        
                        UserList.Attributes.Add("onchange","javascript:formHasChanged();");
                  }

            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            ///            Required method for Designer support - do not modify
            ///            the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.UserList.SelectedIndexChanged += new System.EventHandler(this.UserList_SelectedIndexChanged);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion


            public ITUserCollection DataSource
            {
                  get {return datasource; }
                  set {datasource = value; }
            }

            public string SaveType
            {
                  get {return savetype; }
                  set {savetype = value; }
            }

            public string DDLID
            {
                  get {return ddlId; }
                  set {ddlId = value; }
            }

            public string DBFieldName
            {
                  get {return dbFieldName; }
                  set {dbFieldName = value; }
            }

            public string DataText
            {
                  get {return dataText; }
                  set {dataText = value; }
            }

            public string DataValue
            {
                  get {return dataValue; }
                  set {dataValue = value; }
            }


            public String SelectedValue
            {
                  get {return UserList.SelectedValue; }
                  set {UserList.SelectedValue = value; }
            }

            public void SetSelectedValue (String potentialValue)
            {
                  UserList.SelectedIndex = 0;
                  if (datasource.ContainsKey(potentialValue))
                  {
                        UserList.SelectedValue = potentialValue;
                  }
            }


            public override void DataBind()
            {
                  UserList.Items.Clear();
                  UserList.Attributes.Add("savetype",this.SaveType);
                  UserList.Attributes.Add("dbFieldName",this.DBFieldName);
                  UserList.Attributes.Add("ddlId",this.DDLID);                              
                  UserList.DataSource = datasource;
                  UserList.DataTextField = dataText;
                  UserList.DataValueField = dataValue;
                  UserList.DataBind();
                  UserList.Items.Insert(0, new ListItem( "-- Select User --", "" ) );
                  
            }

            

            public void RemoveDefault()
            {
                  ListItem defaultItem = UserList.Items.FindByValue("0");
                  if (defaultItem != null)
                        UserList.Items.Remove(defaultItem);
            }

            private void UserList_SelectedIndexChanged(object sender, System.EventArgs e)
            {
                  //caused problems when we bind at this point...
                  //this.DataBind();
                  if ( !Page.IsPostBack )
                  {
                        SetSelectedValue( UserList.SelectedValue.ToString() );
                  }

            }



            
      }
}




Hope that helps, if I have left out anything, just let me know....
Avatar of cdfllc

ASKER

Guys, if I find out on the server that the selected index is incorrect, can I "stop" the processing at that point, so my save doesn't go through?
Or is it too late at that point?
How do I "stop" the processing of the server side and just basically go back to the same page?

thanks!
cdfllc
you can stop at any time...