How to make required field validator on dropdownlist? - c#

I have a dropdownlist where I added an extra value to (Choose channel...). If this value is selected I want a message displayed that is required, what I tried is:
<td>
<asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
runat="server" DataTextField="Description" DataValueField="ID">
<asp:ListItem Value="-1" Text="Choose channel..." />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
ControlToValidate="ServiceChannelDropDownList"
InitialValue="-1"
ErrorMessage="*"
</asp:RequiredFieldValidator>
</td>
Unfortunately this just let me select the initial value (which naturally does not exist in the database) without saying it is not allowed. How to solve this?

You need to add the default value in your code behind(.cs) where you bind Dropdownlist data, instead of doing it in .aspx page
ServiceChannelDropDownList.DataBind();
ServiceChannelDropDownList.Items.Insert(0, new ListItem("Choose channel...","-1"));

<td>
<asp:DropDownList ID="ServiceChannelDropDownList" AppendDataBoundItems="true"
runat="server" DataTextField="Description" DataValueField="ID">
<asp:ListItem Value="0" Text="Choose channel..." />
</asp:DropDownList>
<asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
ControlToValidate="ServiceChannelDropDownList"
InitialValue="0"
ErrorMessage="*"
</asp:RequiredFieldValidator>
</td>

I needed to add a ValidationGroup to the RequiredFieldValidator, e.g.,
<asp:RequiredFieldValidator ID="DropDownListRequiredFieldValidator" runat="server"
ControlToValidate="ServiceChannelDropDownList"
InitialValue="0"
ErrorMessage="Channel is required."
ValidationGroup="WorkflowValidation"
CssClass="ValidationCss"
EnableTheming="false">*
</asp:RequiredFieldValidator>
Thanks all for the help!

Related

CompareValidator not working well - ASP.net

I have used compare validator to check whether the selected date is valid or it. The issue here is it only fires up when the submit button is clicked, is it possible to check when the user selects the date.
<tr id="trow" runat="server">
<td class="auto-style3">Need Duration</td>
<td class="auto-style2">
<asp:TextBox ID="TextBox1" runat="server" ReadOnly = "true"></asp:TextBox>
<asp:ImageButton ID="imgJoin" runat="server" ImageUrl="Images/calender.png"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="TextBox1" ErrorMessage="*" ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator></td>
<td>
<asp:TextBox ID="TextBox2" runat="server" ReadOnly = "true"></asp:TextBox>
<asp:ImageButton ID="imgHide" runat="server" ImageUrl="Images/calender.png"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server"
ControlToValidate="TextBox2" ErrorMessage="*" ForeColor="Red"
SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" Operator="GreaterThanEqual"
ControlToValidate="TextBox2" ControlToCompare="TextBox1"
ErrorMessage='Invalid Date'
ForeColor="Red"></asp:CompareValidator>
</td>
</tr>
It has been a while, but I think you need to enable client side validation scripts by adding:
EnableClientScript="True"
Example
<asp:CompareValidator ID="CompareValidator1" EnableClientScript="True" runat="server"
Operator="GreaterThanEqual"
ControlToValidate="TextBox2" ControlToCompare="TextBox1"
ErrorMessage='Invalid Date'
ForeColor="Red"></asp:CompareValidator>
It's documented at msdn.
Aditionally, I do know that custom validators often lack a correct implementation of the javascript. I am not sure how the CompareValidatorbehaves in that sense.
You might need to create a inherited class, to implement the scripts fully. Before going there, try do research a bit.
For example, here is a solution with a custom validator

Validation message error not working properly

I'm having a problem with validation message errors for web forms. I need to get an error when both statements are true(both fields are empty). When I change statement && for || I'm able to get an error but that's not what I want.Thank you. Here is my C# code
protected void CustomValidatorForm_ServerValidate(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrEmpty(drpState.Text) && string.IsNullOrEmpty(txtRegion.Text))
args.IsValid = false;
else
{
args.IsValid = true;
}
}
I'm Trying to run this code for my forms:
<asp:DropDownList ID="drpState" runat="server" CausesValidation="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="IL">Illinois</asp:ListItem>
<asp:ListItem Value="IN">Indiana</asp:ListItem>
<asp:ListItem Value="IA">Iowa</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtRegion" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
</div>
<asp:CustomValidator ID="CustomValidatorList" runat="server"
ControlToValidate ="drpState" OnServerValidate="CustomValidatorForm_ServerValidate"
ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
ForeColor="Red"
>
</asp:CustomValidator>
<asp:CustomValidator ID="CustomValidatorForm" runat="server"
ControlToValidate ="txtRegion" OnServerValidate="CustomValidatorForm_ServerValidate"
ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
ForeColor="Red"
>
</asp:CustomValidator>
try using like this ,
<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ErrorMessage="*" ControlToValidate="txtFrom" runat="server" Display="Dynamic" ForeColor="Red" />
Easy way to do this,
After you create a <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
type <asp:RequiredFieldValidator and press Tab Button twice,
You can also give any ErrorMessage as well as define color of the ErrorMessage
It turns out I just needed to add this property ValidateEmptyText="True" and set it to true. This is how validator should look like:
<asp:CustomValidator ID="CustomValidatorList" runat="server"
ControlToValidate ="drpState" OnServerValidate="CustomValidatorForm_ServerValidate"
ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
ForeColor="Red" ValidateEmptyText="True">
</asp:CustomValidator>

RequiredFieldValidator not working for tow Dropdownlist

I have tow Dropdownlist in my web page as follows.
<asp:DropDownList ID="JobDDL" runat="server" class="form-control" ValidationGroup="gg" >
</asp:DropDownList>
<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic"
ValidationGroup="gg" runat="server" ControlToValidate="JobDDL"
Text="*" ErrorMessage="أختر الفرع من فضلك"></asp:RequiredFieldValidator>
<asp:DropDownList ID="BranchDDL" runat="server" class="form-control">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="BranchDDL" ErrorMessage="أختر الفرع من فضلك" InitialValue="اختر من فضلك" ForeColor="red"></asp:RequiredFieldValidator>
frist Dropdownlist RequiredFieldValidator (ID="JobDDL") not work . The second RequiredFieldValidatorworks(ID="BranchDDL")
Please add Display="Dynamic" and Initial value="Select" in Required Field Validator
if your dropdown list first element has select values please Add Initial Value="Select" in Required Field Validator.
<asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Please Select Type" InitialValue="--Select--" Font-Bold="True" ForeColor="#CC0000" Display="Dynamic"></asp:RequiredFieldValidator>

Asp.net Gridview CompareValidator

I have a GridView with multiple rows (records).
<asp:DropDownList ID="DDLActionStatus" runat="server" DataSourceID="LDSActionStatus" AppendDataBoundItems="True" DataTextField="Title" DataValueField="ReportActionStatusID" SelectedValue='<%# Bind("ReportActionStatusID") %>' Enabled='<%# (int)Eval("ReportActionStatusID") == 1 %>' Width="100%" />
<asp:Button ID="BtnActionStatus" runat="server" CommandName="Update" Text="Save & Close" OnClientClick="return confirm('Are you sure? Once set, this can not be changed.')" Width="100%" />
<asp:CompareValidator ID="CVActionStatus" runat="server" Operator="NotEqual" ValueToCompare="1" Type="Integer" ControlToValidate="DDLActionStatus" SetFocusOnError="true" ErrorMessage="Must set one of the Completion statuses" />
It works fine for one row, however if there are multiple rows it validates all rows together.
I understand it happens because the ControlToValidate="DDLActionStatus" repets for each row.
I tried to set the ID like ID="DDLActionStatus<%# Eval('ReportActionStatusID') %>" and the ControlToValidate="DDLActionStatus<%# Eval('ReportActionStatusID') %>", but it doesn't work.
I know I could write a custom validation, but is there an easy solution that doesn't require a custom validation?
What I need is to each row be validate independent.
Thanks for help.
The issue is not with the ControlToValidate property. Add a ValidationGroup property to each control in a row with same value. But, make sure to keep it unique for all rows in your GridView. See following example.
<asp:DropDownList ID="DDLActionStatus" runat="server" ValidationGroup="MyGroup1" DataSourceID="LDSActionStatus" AppendDataBoundItems="True" DataTextField="Title" DataValueField="ReportActionStatusID" SelectedValue='<%# Bind("ReportActionStatusID") %>' Enabled='<%# (int)Eval("ReportActionStatusID") == 1 %>' Width="100%" />
<asp:Button ID="BtnActionStatus" runat="server" ValidationGroup="MyGroup1" CommandName="Update" Text="Save & Close" OnClientClick="return confirm('Are you sure? Once set, this can not be changed.')" Width="100%" />
<asp:CompareValidator ID="CVActionStatus" runat="server" ValidationGroup="MyGroup1" Operator="NotEqual" ValueToCompare="1" Type="Integer" ControlToValidate="DDLActionStatus" SetFocusOnError="true" ErrorMessage="Must set one of the Completion statuses" />
Make sure ValidationGroup is different for each row.
All the best!

Validation Group used to validate the group not show the error message

In the form in aspx I have two textbox and one image button for each textbox.
I need validation the value for each textbox in a separate way and for this I have for each image button linked to a different event.
For this I have finded in google and I have tried this tutorial:
http://www.c-sharpcorner.com/Blogs/3625/use-of-validation-group-in-Asp-Net.aspx
But in my form the Validation Group in asp.net not working and I don't understand the reason.
What does not work are the warning messages that indicate required fields.
What's wrong?
My code aspx below, thank you in advance.
<form id="form1" runat="server">
<div>
<asp:textbox id="TextBox1" runat="server" width="100" cssclass="ddl_Class" validationgroup="First"></asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator3" runat="server" controltovalidate="TextBox1"
errormessage="Error in TextBox1" text="***" display="None" validationgroup="First"></asp:requiredfieldvalidator>
<asp:regularexpressionvalidator id="RegularExpressionValidator4" runat="server" controltovalidate="TextBox1"
errormessage="TextBox1 only number" text="***" display="None" validationexpression="^\d+$" validationgroup="First"></asp:regularexpressionvalidator>
<asp:imagebutton id="btnSave1" runat="server" validationgroup="First" onclick="ButtonSave1_Click" imageurl="/Images/save_button.gif" onclientclick="if (!confirm('Confirm?')) return false;" />
<asp:textbox id="TextBox2" runat="server" width="100" cssclass="ddl_Class" validationgroup="Second"></asp:textbox>
<asp:requiredfieldvalidator id="RequiredFieldValidator4" runat="server" controltovalidate="TextBox2"
errormessage="Error " text="***" display="None" validationgroup="Second"></asp:requiredfieldvalidator>
<asp:imagebutton id="btnSave2" runat="server" validationgroup="Second" onclick="ButtonSave2_Click" imageurl="/Images/save_button.gif" onclientclick="if (!confirm('Confirm?')) return false;" />
</div>
<asp:validationsummary id="First" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
<asp:validationsummary id="Second" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
</form>
I have verified your code, only problem that I identified is missing validation group in validation summary tag.
See below:
<asp:validationsummary id="First" validationgroup="First" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
<asp:validationsummary id="Second" validationgroup="Second" runat="Server" showmessagebox="true" cssclass="validation-summary-errors" />
Hope this will work

Categories