RequiredValidation only active when another control contain a value - asp.net

I have two dropdownlists, if one of them contain a value (not default value, which is empty string), the other should also have a value (like requredvalidator). But if no one has a value the page should validate 'true'.
I cannot solve it with a validation group, because the button that trigger the validation is already triggering other validations.

Could you just use a custom validator control and put your logic in the server side validation method. Keep it in the same validation group.
<asp:CustomValidator ID="valCust" runat="server"
ControlToValidate="ddlControl" ErrorMessage="error Message"
ValidationGroup="Group"
onservervalidate="valCust_ServerValidate" >*</asp:CustomValidator>
code behind
protected void valCust_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = MethodToWorkOutValidation();
}

please check below code snippet.
function EnableDisableValidator() {
var DropDownList1 = document.getElementById('DropDownList1');
var DropDownList2 = document.getElementById('DropDownList2');
var RequiredFieldValidator12 = document.getElementById('RequiredFieldValidator12');
if (DropDownList1.selectedIndex > 0 && DropDownList2.selectedIndex > 0) {
ValidatorEnable(document.getElementById('RequiredFieldValidator12'), true);
}
else {
ValidatorEnable(document.getElementById('RequiredFieldValidator12'), false);
}
}
..........
<asp:DropDownList ID="DropDownList1" runat="server" onchange="EnableDisableValidator();">
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" onchange="EnableDisableValidator();">
<asp:ListItem Text="" Value=""></asp:ListItem>
<asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
<div style="display: none;">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ControlToValidate="TextBox1"
Enabled="false" ErrorMessage="*************" ></asp:RequiredFieldValidator>
Let me know if any concern

Related

How to Use Required Field validator on a check box CHECKED true or false

I have a user setting form on which there is a dropdownlist to change some kind of user setting, on the other hand I have a check box to change a password also or not on the same page. When check box is check
<asp:CheckBox ID="cbPassword" runat="server" CssClass="checkbox" onclick="showhidepasswordFields()" />
<div class="col-xs-9 form-inline" id="PChange" style="display: none;">
<asp:TextBox ID="tbxOldPass" runat="server" TextMode="Password" CssClass="form-control" Width="122px"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Enter Old Password" ForeColor="Red" ControlToValidate="tbxOldPass" ValidationGroup="grp"></asp:RequiredFieldValidator>
<asp:TextBox ID="tbxNewPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="tbxNewPassRFV" runat="server" ControlToValidate="tbxNewPass" ErrorMessage="Enter New Passwod" ForeColor="Red" ValidationGroup="grp"></asp:RequiredFieldValidator>
<asp:TextBox ID="tbxConfirmPass" runat="server" TextMode="Password" Width="122px" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic" ControlToValidate="tbxConfirmPass" ErrorMessage="Reconfirm Password" ForeColor="Red" ValidationGroup="grp" ></asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" Display="Dynamic" ErrorMessage="Paswords are not Same" ForeColor="Red" ControlToCompare="tbxNewPass" ControlToValidate="tbxConfirmPass" ValidationGroup="grp"></asp:CompareValidator>
</div>
gets visible where user have to enter old and new password. I want that when check box is checked then required field validator works other wise not.
<asp:Button ID="tbnUpdate" runat="server" Text="Update" OnClick="tbnUpdate_Click" CssClass="btn btn-success" CausesValidation="false" ValidationGroup="grp" />
If I set CausesValidation="false" then validation is not done. If i set it true then if checkbox is not checked validator triggers. Is there there any way that valdation only done when check box is checked other wise just update the setting from drop down list?
Java script function to show/hide div.
<script type="text/javascript">
function showhidepasswordFields() {
if (document.getElementById('<%=cbPassword.ClientID%>').checked) {
document.getElementById('PChange').style.display = 'block';
}
else if (!document.getElementById('<%=cbPassword.ClientID%>').checked) {
document.getElementById('PChange').style.display = 'none';
}
}
</script>
You can use a CustomValidator for that. The first function just test wether the CheckBox is checked or not. The other one adds more logic like checking if a TextBox also has a value. Just change the ClientValidationFunction for testing.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ClientValidationFunction="testCheckBoxAndTextBox"></asp:CustomValidator>
<script type="text/javascript">
function testCheckBox(sender, element) {
element.IsValid = $("#<%= CheckBox1.ClientID %>").prop('checked');
}
function testCheckBoxAndTextBox(sender, element) {
var isValid = false;
if ($("#<%= CheckBox1.ClientID %>").prop('checked') == true && $("#<%= TextBox1.ClientID %>").val() != "") {
isValid = true;
}
element.IsValid = isValid;
}
</script>
.aspx:
<asp:CheckBox ID="cbTest" runat="server" OnCheckedChanged="cbTest_CheckedChanged"></asp:CheckBox>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqFV" Enabled="false" runat="server" ErrorMessage="*****" ControlToValidate="txtTest" ></asp:RequiredFieldValidator>
.aspx.cs:
protected void cbTest_CheckedChanged(object sender, EventArgs e)
{
reqFV.Enabled = cbTest.Checked;
}

validate a combination of different fields

aspx page
<asp:Label ID="Label1" runat="server" Text="Date of Birth: "></asp:Label>
<asp:Label ID="dob_msg_lbl" runat="server" Font-Size="Medium" ForeColor="Red" Text="invalid date of birth" visible="False"></asp:Label>
<br />
<asp:TextBox ID="day_tb" runat="server" MaxLength="2" Width="15px"></asp:TextBox> <asp:Label ID="Label4" runat="server" Text="/" Font-Bold="True"></asp:Label>
<asp:DropDownList ID="month_ddl" runat="server">
<asp:ListItem Value=""></asp:ListItem>
<asp:ListItem Value="Jan">January</asp:ListItem>
<asp:ListItem Value="Feb">Feb</asp:ListItem>
<asp:ListItem Value="Mar">Mar</asp:ListItem>
<asp:ListItem Value="Apr">Apr</asp:ListItem>
<asp:ListItem Value="May">May</asp:ListItem>
<asp:ListItem Value="Jun">Jun</asp:ListItem>
<asp:ListItem Value="Jul">Jul</asp:ListItem>
<asp:ListItem Value="Aug">Aug</asp:ListItem>
<asp:ListItem Value="Sep">Sep</asp:ListItem>
<asp:ListItem Value="Oct">Oct</asp:ListItem>
<asp:ListItem Value="Nov">Nov</asp:ListItem>
<asp:ListItem Value="Dec">Dec</asp:ListItem>
</asp:DropDownList> <asp:Label ID="Label5" runat="server" Text="/" Font-Bold="True"></asp:Label> <asp:TextBox ID="year_tb" runat="server" Width="30px" MaxLength="4"></asp:TextBox>
aspx.vb page
Dim dobStr As String = day_tb.Text + " " + month_ddl.SelectedValue + " " + year_tb.Text
Try
dob = Convert.ToDateTime(dobStr)
Catch ex As Exception
dob_msg_lbl.Visible = True
End Try
Currently I am mimicking the asp.net's validation functions by setting dob_msg_lbl.visible to true when Convert.ToDateTime results in an exception.
The problem with such a method is that the validation only occurs when the form is submitted.
I want to validate it on the fly, just like what happens when you use RequiredFieldValidator and RegularExpressionValidator.
Is it to possible to use something such as the CustomValidator to validate a combination of textbox and dropdownlist on the fly?
You can try to use CustomerValidator as explained here
http://www.codeproject.com/Articles/9522/CustomValidator-dependent-on-multiple-controls
Or
you can create a validate function with your logic, and call it on the Selection change event for dropdown and text change event of TextBox. So anytime, any of those thing changes that will trigger the event and will call your validate function.

ASP.NET: RequiredFieldValidator with Multiple TextBoxes in ListView

I have a ListView
<asp:ListView ....>
<asp:TextBox ID="txtComment" ... />
<asp:RequiredFieldValidator ID="rfvComment" ControlToValidate="txtComment" ... />
<act:ValidatorCalloutExtender ID="vceComment" TargetControlID="rfvComment" ... />
<asp:Button ID="btnAddComment" ... />
</asp:ListView>
lets say this ListView creates the following:
TextBox1
Button1
TextBox2
Button2
TextBox3
Button3
If I click on Button2 the RequiredFiledValidator/ValidatorCalloutExtender are applied to TextBox1 instead of TextBox2, if I click on Button3 the RequiredFiledValidator/ValidatorCalloutExtender are applied to TextBox1 as well, I want the RequiredFiledValidator/ValidatorCalloutExtender to apply to the TextBox next to the button, so if I click Button3 I want it to apply to TextBox3.
Does anyone know how can I achieve this?
thank you.
Use ValidationGroup property and generate it value dynamically:
<asp:TextBox runat="server" ID="TextBox1" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TextBox1" Text="*"
ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />
<asp:Button runat="server" Text="Click Me" ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />
Add script below at very bottom of form:
<script type="text/javascript">
var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
ValidatorUpdateDisplay = function (val) {
originalValidatorUpdateDisplay.call(null, val);
var isHidden = val.style.display == "none" || val.style.visibility == "hidden";
var extender = Sys.UI.Behavior.getBehaviorsByType(val, Sys.Extended.UI.ValidatorCalloutBehavior);
if (extender && extender.length == 1) {
extender = extender[0];
if (isHidden) {
extender.hide();
}
else {
extender.show(true);
}
}
}
</script>
I suppose it would be better to customize toolkit source, but I'm not in the mood to do this :) So hope this script will fix your problem
try smth like (example, that should work)
<asp:Panel ID="registration" defaultbutton="regButton" runat="server">
<asp:TextBox ID="name" Rows="1" CssClass="text" runat="server" ValidationGroup="Registration">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter your name please" Text="*" ControlToValidate="name" EnableClientScript="False" Display="Dynamic" ValidationGroup="Registration" />
<asp:TextBox ID="address" Rows="1" CssClass="text" runat="server" ValidationGroup="Registration"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter your address please" Text="*" ControlToValidate="address" EnableClientScript="False" Display="Dynamic" ValidationGroup="Registration" />
<asp:ValidationSummary DisplayMode="BulletList" EnableClientScript="false" ID="validation_sum" runat="server" HeaderText="Errors list" ValidationGroup="Registration"/>
<asp:Button runat="server" id="regButton" Text="Register please" ValidationGroup="Registration" OnClick="RegisterUser"/>
</asp:Panel>

How to send extra parameter on SelectedIndexChanged?

Is there any way to send extra parameter to SelectedIndexChanged function?
<asp:RadioButtonList
ID="rblMeetingPlace"
SelectedValue = '<%# Bind("intMtgLoc") %>'
*OnSelectedIndexChanged = "Validate('txtMeetPlaceOther')"*
runat="server"
RepeatDirection="Horizontal"
>
<asp:ListItem Value="1">Workshop</asp:ListItem>
<asp:ListItem Value="2">Service provider agency</asp:ListItem>
<asp:ListItem Value="3">Advocacy organization</asp:ListItem>
<asp:ListItem Value="4">Public Space</asp:ListItem>
<asp:ListItem Value="5">Other (specify): </asp:ListItem>
<asp:ListItem Value="" Text="" style="display: none" />
</asp:RadioButtonList>
<asp:TextBox ID="txtMeetPlaceOther" Text='<%# Bind("strMtgLocOth") %>'
runat="server" />
I have couple of radiobuttonlist and I want to enable the textboxes when "Other" is selected.
I am thinking of sending the textbox's id to enable it.
Any idea?
You can easily do it this way:
<asp:radiobuttonlist id="rbl1" runat="server"
RepeatDirection="Horizontal"
AutopostBack="true"
SelectedValue='<%# Bind("intMtgLoc") %>'
OnselectedIndexChanged="rbl1_SelectedIndexChanged">
<asp:ListItem Value="1">Workshop</asp:ListItem>
<asp:ListItem Value="2">Service provider agency</asp:ListItem>
<asp:ListItem Value="3">Advocacy organization</asp:ListItem>
<asp:ListItem Value="4">Public Space</asp:ListItem>
<asp:ListItem Value="5">Other (specify): </asp:ListItem>
<asp:ListItem Value="" Text="" style="display:none" />
</asp:radiobuttonlist>
<asp:textbox id="txtMeetPlaceOther" text='<%# Bind("strMtgLocOth") %>' runat="server" />
<asp:textbox id="TextBox1" enabled="false" runat="server"></asp:textbox>
<asp:textbox id="TextBox2" enabled="false" runat="server"></asp:textbox>
and in code-behind:
protected void rbl1_SelectedIndexChanged(object sender, EventArgs e)
{
*yourValidatorName*.Validate();
if (Convert.ToInt32(rbl1.SelectedValue) == 5)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
}
else
{
TextBox1.Enabled = false;
TextBox2.Enabled = false;
}
}
reply to comment:
First of all you should set OnSelectedIndexChanged for all RadioButtonLists event handlers. Here - rbl_SelectedIndexChanged.
Then in code behind:
protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox[] textboxes = new TextBox[] { TextBox1, TextBox2 };//all your textboxes.
RadioButtonList whoCallEvent = sender as RadioButtonList;
string last = whoCallEvent.ID.ToString().Substring(whoCallEvent.ID.ToString().Length - 1, 1);//get the last symbol of object (TextBox) ID, who call event.
int index = Convert.ToInt32(last);
if (Convert.ToInt32(whoCallEvent.SelectedValue) == 5)
{
textboxes[index - 1].Enabled = true;
}
else
{
textboxes[index - 1].Enabled = false;
}
}
But I think this is conceptually wrong to do it this way. The best way is to create rbl_SelectedIndexChanged for all the radioButtonList you have on my page.

Working with dropdown list & Validation in asp.net

I have got a dropdown list populated with products from a product table. I have a button named ADD Product, so when the user wants to add a new product instead of selecting product from the drop down list, one should click on add new then panel 1 should show which includes a textbox. Panel1 visibility is set to false by default and it should be visible when the user clicks on the button. Also I want a validation on dropdown list and textbox(if panel is visible). Below is the code which is not working :
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<%--<asp:TextBox ID="txtMake" runat="server" CssClass="txtStyle"></asp:TextBox>--%>
<asp:Button ID="btnAdd" runat="server" />
<asp:Panel ID="panel1" Visible="false" runat="server"><asp:TextBox ID="txtAddnew"></asp:TextBox></asp:Panel>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please Select a Product" ValidationGroup="insert" ControlToValidate="DropDownList1" ForeColor="Red"></asp:RequiredFieldValidator><br />
codebehind:
protected void btnAdd_Click(object sender, EventArgs e)
{
panel1.Visible = true;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MultiView1.ActiveViewIndex = 0;
DropDownList1.DataSource = caravans.GetProductNames();
DropDownList1.DataBind();
}
}
You can use this concept for validation on dropdownlist. I am given you an example please check this...
<asp:DropDownList runat="server" ID="ddl">
<asp:ListItem Value="-1" Text="Select"></asp:ListItem>
<asp:ListItem Value="1" Text="One"></asp:ListItem>
<asp:ListItem Value="2" Text="Two"></asp:ListItem>
</asp:DropDownList>
<asp:RegularExpressionValidator ID="reg1" runat="server" ControlToValidate="ddl"
Display="Dynamic" ErrorMessage="Select Proper" SetFocusOnError="true" Text="Select Proper"
ValidationGroup="check" ValidationExpression="^\d{0,5}$" />
<asp:Button ID="btn" runat="server" ValidationGroup="check" Text="Submit" />

Resources