Dropdownlist validation in Asp.net Using Required field validator - asp.net

I have Dropdownlist whose value field and text field are bind at runtime.
it has --select-- as first item with a value of 0
and the rest of the values are bind at runtime.
I have given validaton group for both the control and the validator as "g1"
and Intialvalue=0
But still the page is posting back even if I select --select-- option.
<asp:DropDownList AutoPostBack="true" CssClass="dropdown" ValidationGroup="g1"
ID="ddlReportType" runat="server"
OnSelectedIndexChanged="ddlReportType_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator ControlToValidate="ddlReportType" ID="RequiredFieldValidator1"
ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
InitialValue="0" runat="server" Display="Dynamic">
</asp:RequiredFieldValidator>
And code Behind to Bind the Dropdown
ddlReportType.Items.Clear();
ddlReportType.DataSource = dt.Tables[0];
ddlReportType.DataTextField = "ReportType";
ddlReportType.DataValueField = "ReportTypeID";
ddlReportType.DataBind();
ddlReportType.Items.Insert(0, new ListItem("--Select--", "0"));
//ddlReportType.Items[0].Value = "0";
ddlReportType.SelectedIndex = 0;

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

Here use asp:CompareValidator, and compare the value to "select" option.
Use Operator="NotEqual" ValueToCompare="0" to prevent the user from submitting the "select".
<asp:CompareValidator ControlToValidate="ddlReportType" ID="CompareValidator1"
ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
runat="server" Display="Dynamic"
Operator="NotEqual" ValueToCompare="0" Type="Integer" />
When you do above, if you select the "select " option from dropdown it will show the ErrorMessage.

I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:
<asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Expired</asp:ListItem>
<asp:ListItem>Lost/Stolen</asp:ListItem>
<asp:ListItem>Location Change</asp:ListItem>
</asp:DropDownList>
However adding the InitialValue like this worked instantly for a compare Validator.
<asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>

Add InitialValue="0" in Required field validator tag
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID"
Display="Dynamic" ValidationGroup="g1" runat="server"
ControlToValidate="ControlID"
InitialValue="0" ErrorMessage="ErrorMessage">
</asp:RequiredFieldValidator>

Related

Field validation as required only if true

I have such a Checkbox and DropDownList with Validator
<asp:CheckBox ID="chkIncludeLogin" runat="server" Text='MyCheckBox' Font-Size="9pt"/>
<asp:DropDownList ID="ddlLanguage" runat="server" ViewStateMode="Enabled" ></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldLanguage" runat="server" ControlToValidate="ddlLanguage"
InitialValue="-1" SetFocusOnError="True" ForeColor="Red" ValidationGroup="check"
Display="Dynamic" Text='*'></asp:RequiredFieldValidator>
I have this problem:
When I do not check CheckBox and do further actions, Validator does not start and everything works fine
When I check CheckBox and uncheck it, Validator works and does not allow to perform other actions.
How to make the validator not take this field into account when I check and uncheck the CheckBox?

RegularExpressionValidator in Asp.net

I have search textbox,which has default value Enter Month to View Profit. When I click search button without entering any data, the default value of textbox is posted to server for search. I want that RegularExpressionValidator do not validate default value of textbox.
<asp:TextBox ID="Tboxsearch" Text="Enter Month to View Profit" OnClick="this.value=''" CssClass="textboxinput" runat="server"></asp:TextBox>
<asp:Button ID="ButtonSearch" CssClass="btnLog" runat="server" Text="Search" onclick="ButtonSearch_Click" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorname"
runat="server"
ControlToValidate="Tboxsearch"
ForeColor="Red"
Text="*"
>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidatorname"
runat="server"
ValidationExpression="[a-zA-Z0-9]+"
ForeColor="Red"
ControlToValidate="Tboxsearch"
ErrorMessage="Enter Valid Name!"
>
</asp:RegularExpressionValidator>
The default for all validators except the RequiredFieldValidator control if you post with empty field the validator will not trigger
you must use required field validator with other validators to prevent the postback to happen
from MSDN
Special-Case Validation Results for ASP.NET Server Controls
EDIT
Also if you add your controls as in your question it should work but if there is other controls like for example other button you should set the validationGroup Property to the group that you want to work together
ValidationGroup="vGrp"
and your code will be like this
<asp:TextBox ID="Tboxsearch" Text="Enter Month to View Profit" OnClick="this.value=''" CssClass="textboxinput" runat="server" ValidationGroup="vGrp"></asp:TextBox>
<asp:Button ID="ButtonSearch" CssClass="btnLog" runat="server" Text="Search" onclick="ButtonSearch_Click" ValidationGroup="vGrp" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorname"
runat="server"
ControlToValidate="Tboxsearch"
ForeColor="Red"
Text="*"
ValidationGroup="vGrp">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator
ID="RegularExpressionValidatorname"
runat="server"
ValidationExpression="[a-zA-Z0-9]+"
ForeColor="Red"
ControlToValidate="Tboxsearch"
ErrorMessage="Enter Valid Name!" ValidationGroup="vGrp"></asp:RegularExpressionValidator>
from MSDN about validationGroup

Validating drop down list

I Have a dropdownlist in an aspx page, I am populating the dropdownlist using a datatable. How can i apply a requiredfield validator to this dropdownlist.? Plz help me
You have to set the InitialValue for the selected item's Value that is selected first:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList1"
InitialValue="-- Please select --"
ErrorMessage="Please select something" />
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
<asp:ListItem>-- Please select --</asp:ListItem>
</asp:DropDownList>

RequiredFieldValidator for a dropdown list populated by an SQLDataSource

Morning All,
I have a dropdown list that is populated by an SQLSataSource. I wish to make this dropdown list a required field and need to add add a default item like -Please Select- at the top of this list to prompt the user to make a selection.
Here is my code...
<asp:DropDownList ID="ddOwner" runat="server" DataSourceID="OwnersList"
DataTextField="UserFullName" DataValueField="UserFullName" Height="24px"
Width="125px">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvOwner"
ControlToValidate="ddOwner"
ErrorMessage="Please assign an Owner"
Text="*"
runat="server" Display="None"/>
Can i add some code into the 'Initial value' item to set the -Please select- default item?
Regards Betty
Add an unbound item:
<asp:DropDownList ID="ddOwner" runat="server" DataSourceID="OwnersList"
DataTextField="UserFullName" DataValueField="UserFullName" Height="24px"
AppendDataBoundItems="true"
Width="125px">
<asp:ListItem Text="-Please Select-" Value="" />
</asp:DropDownList>
You can try with after your DataBind Method
...
ddOwner.DataBind();
ddOwner.Items.Add("Please select- default item?");

How to add a RequiredFieldValidator to DropDownList control?

I have a DropDownList binded with aSqlDataSource to display the values from the database.
I am unable to validate using a RequiredFieldValidator.
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
If you are using a data source, here's another way to do it without code behind.
Note the following key points:
The ListItem of Value="0" is on the source page, not added in code
The ListItem in the source will be overwritten if you don't include
AppendDataBoundItems="true" in the DropDownList
InitialValue="0" tells the validator that this is the value that
should fire that validator (as pointed out in other answers)
Example:
<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType"
InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server"
ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>
InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.
<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />

Resources