Customvalidator: Check if radiobuttonlist contains a selected item - asp.net

I have a radiobuttonlist with two items, Yes or No. The radiobuttonlist control has a customvalidator that needs a servervalidation function and a javascript clientvalidationfunction. Could you help me? The function in this message works but only when i actually have choosen one of the two listitems, when no listitem is selected the validation skips my radiobuttonlist control.
function ValidateRadioButtonList(source, arguments) {
var RBL = document.getElementById(source.controltovalidate);
var radiobuttonlist = RBL.getElementsByTagName("input");
var counter = 0;
var atLeast = 1
for (var i = 0; i < radiobuttonlist.length; i++) {
if (radiobuttonlist[i].checked) {
counter++;
}
}
if (atLeast = counter) {
arguments.IsValid = true;
return arguments.IsValid;
}
arguments.IsValid = false;
return arguments.IsValid;
}
EDIT: Relevant code from comments
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btnNormal"
CausesValidation="True" />
<asp:CustomValidator runat="server"
ClientValidationFunction="ValidateRadioButtonList"
OnServerValidate="RadioButtonListServerValidation" ID="cvRadioButtonList"
Font-Bold="True" Font-Size="Medium" ErrorMessage="Business critical"
ControlToValidate="rblBusinessCritical">*</asp:CustomValidator>
<asp:RadioButtonList ID="rblBusinessCritical" runat="server" RepeatLayout="Flow"
RepeatDirection="Horizontal" TabIndex="4">
<asp:ListItem Text="Yes" Value="1" />
<asp:ListItem Text="No" Value="0" />
</asp:RadioButtonList>
Code Behind:
Public Sub RadioButtonListServerValidation(ByVal sender As Object, _
ByVal args As ServerValidateEventArgs)
If rblBusinessCritical.SelectedValue = "-1" Then
args.IsValid = False
cvRadioButtonList.ErrorMessage = "Business critical needed"
Exit Sub
Else
args.IsValid = True
End If
End Sub

Have you set the ValidateEmptyText Property of the CustomValidator to true?
edit:
Have you set the CausesValidation Property of your Submit-Button/RadioButtonList to true?
Please provide some code from your aspx-page.

Here is another javascript clientvalidation function i have tried:
function ValidateRadioButtonList(source, arguments) {
var RBL = document.getElementById(source.controltovalidate);
var radio = RBL.getElementsByTagName("input");
var isChecked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select an item");
arguments.IsValid = false;
}
arguments.IsValid = true;
}

Do you need to use client-side?
Here is a server-side solution...
<asp:RadioButtonList id="radTerms" runat="server">
<asp:listitem id="optDisagree" runat="server" value="Disagree" selected="true">I don't agree</asp:ListItem>
<asp:listitem id="optAgree" runat="server" value="Agree">I agree</asp:ListItem>
</asp:RadioButtonList>
<asp:CustomValidator Display="Dynamic" ErrorMessage="You have to agree to the terms and conditions" ID="cmpTerms" ControlToValidate="radTerms" SetFocusOnError="true" runat="server" OnServerValidate="cmpTermsAccepted_ServerValidate">*</asp:CustomValidator>
CodeBehind:
protected void cmpTermsAccepted_ServerValidate(Object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
args.IsValid = (args.Value == "Agree");
}

That should work. Trying taking the control to validate property off the customer validator.

<asp:RadioButtonList ID="LocationAccurateRBL" CssClass="radioButtonList" RepeatDirection="Horizontal" RepeatColumns="4" RepeatLayout="Flow" runat="server">
<asp:ListItem Text="Yes" Value="1" />
<asp:ListItem Text="No" Value="0" />
</asp:RadioButtonList>
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true" ControlToValidate="LocationAccurateRBL"
ClientValidationFunction="LocationAccurate_ClientValidate" ValidateEmptyText="true"
Text="*" ForeColor="Red" ErrorMessage="Please let us know if the location is accurate" SetFocusOnError="true" ValidationGroup="CreateVG" />
And the script, is much shorter because of jquery. This will do what you want.
<script>
function LocationAccurate_ClientValidate(sender, e) {
e.IsValid = $("#<%=LocationAccurateRBL.ClientID%> > input").is(':checked');
}
</script>

Related

website /url validation in asp.net not working

<asp:RegularExpressionValidator ID="revWebsite" runat="server" ForeColor="Red"
ControlToValidate="txtWebsite" ErrorMessage="Invalid Website (General Details)"
ValidationExpression="(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?">*
</asp:RegularExpressionValidator>
why not working for ? :
www.website.com
www.domain.website.com
http://website.com
https://website.com
Suggestion: if you want to validate a site a you can check its existence by pining it.
you can use custom validator for that. for that see the below example:
in the .aspx page:
<div>
<asp:TextBox runat="server" ID="txtURL" ValidationGroup="vlg" />
<asp:RequiredFieldValidator ID="rqfvURL" ErrorMessage="Please Enter" ControlToValidate="txtURL" ValidationGroup="vlg"
runat="server" />
<asp:CustomValidator ID="cstmValURL" ErrorMessage="Please enter valid site"
ControlToValidate="txtURL" runat="server" ValidationGroup="vlg"
onservervalidate="cstmValURL_ServerValidate" />
<asp:Button Text="submit" ID="btn" runat="server" onclick="btn_Click" ValidationGroup="vlg" />
</ div>
in the .cs page:
protected void cstmValURL_ServerValidate(object source, ServerValidateEventArgs args)
{
if (TestSite())
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
private bool TestSite()
{
Ping objPing = new Ping();
bool blnResult = false;
try
{
PingReply pngReply = objPing.Send(txtURL.Text.Trim(), 3000);
if (pngReply.Status == IPStatus.Success)
return blnResult= true;
}
catch
{
return blnResult=false;
}
return blnResult;
}
P.S. This is just a suggestion.

Firing ImageButton server side event but the page is not updating using ASP.NET UpdatePanel

I've feature to implement which is when user in the GridView footer and press on Enter key the row will be inserted. In the GridView I have 2 <asp:ImageButton> one in <EmptyDataTemplate> and the other in <FooterTemplate> I wrote JavaScript to execute the ImageButton Click event when use is in the last field, the ImageButton Server-Side Click event fired but the page is not updated.
Here is JavaScrip function:
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
button.click();
}
}
Here is the ASPX:
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
...
<asp:GridView ID="grvDonationDist" runat="server" AutoGenerateColumns="False" ShowFooter="True"
DataKeyNames="reciept_num,donation_code" meta:resourcekey="grvDonationDistResource1"
ShowHeaderWhenEmpty="True" BorderWidth="1px" BackColor="White" BorderColor="LightSteelBlue"
CellPadding="0" Font-Name="tahoma" Font-Size="10pt" ForeColor="DarkBlue" HeaderStyle-BackColor="#aaaadd"
GridLines="None">
<EmptyDataTemplate>
<asp:Label CssClass="label" ID="lblEmptyDonationDist" runat="server" Text="No Donations"
meta:resourcekey="lblEmptyDonationDistResource1"></asp:Label>
<tr>
<td>
<asp:ImageButton ID="lbtnAdd" runat="server" OnClick="lbtnAdd_Click" meta:resourcekey="AddResource1"
ImageUrl="Content/images/add.png"></asp:ImageButton>
</td>
...
<td>
<asp:TextBox ID="txtDonationNotesFooter" CssClass="textbox" runat="server" meta:resourcekey="txtDonationNotesResource1"
onKeyDown="insertByEnterKey('lbtnAdd');"></asp:TextBox>
</td>
</tr>
</EmptyDataTemplate>
<Columns>
<asp:TemplateField FooterText="Total" ShowHeader="False">
<EditItemTemplate>
...
</EditItemTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="lbtnAdd" runat="server" OnClick="lbtnAddFromFooter_Click" meta:resourcekey="AddResource1"
ImageUrl="Content/images/add.png"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Notes" SortExpression="distribution_remrks" meta:resourcekey="TemplateFieldResource3">
<EditItemTemplate>
...
</EditItemTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDonationNotesFooter" CssClass="textbox" runat="server" meta:resourcekey="txtDonationNotesResource1"
onKeyDown="insertByEnterKey('lbtnAdd');"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Here is VB.NET:
Protected Sub lbtnAddFromFooter_Click(sender As Object, e As EventArgs)
'Footer Add
'Add Insert Logic here
Try
Dim donationDist As New DonationDist
Dim txtDonationValueFooter As TextBox = grvDonationDist.FooterRow.FindControl("txtDonationValueFooter")
Dim txtDonationNotesFooter As TextBox = grvDonationDist.FooterRow.FindControl("txtDonationNotesFooter")
Dim ddlCountryFooter As DropDownList = grvDonationDist.FooterRow.FindControl("ddlCountryFooter")
Dim ddlPurposeFooter As DropDownList = grvDonationDist.FooterRow.FindControl("ddlNewDonationPurposeType")
Dim chkPartial As CheckBox = grvDonationDist.FooterRow.FindControl("chkPartialFooter")
Dim standInstruct As Label = grvDonationDist.FooterRow.FindControl("lblStandInstructFooter")
Dim donationValue As Decimal = Convert.ToDecimal(txtDonationValueFooter.Text)
'Validation: Donation Value must be > 0
If (donationValue <= 0) Then
If (CultureInfo.CurrentUICulture.Name.Contains("ar")) Then
ShowAlert("قيمة الترع يجب ان تكون أكبر من الصفر")
ElseIf (CultureInfo.CurrentUICulture.Name.Contains("en")) Then
ShowAlert("Donation Value must be greater than 0")
End If
Exit Sub
End If
myDonationDistDataTable = Session("myDonationDistDataTable")
'Validation: Only one donation type per Receipt
For Each row As DataRow In myDonationDistDataTable.Rows
If (row.Item("donation_code") = ddlPurposeFooter.SelectedValue) Then
If (CultureInfo.CurrentUICulture.Name.Contains("ar")) Then
ShowAlert("لا يمكن تكرار الغرض في نفس سند القبض")
ElseIf (CultureInfo.CurrentUICulture.Name.Contains("en")) Then
ShowAlert("You cannot add more than on Donation Type per receipt")
End If
Exit Sub
End If
Next
myDonationDistDataRow = myDonationDistDataTable.NewRow()
myDonationDistDataRow("reciept_num") = 0
myDonationDistDataRow("donation_code") = Convert.ToInt16(ddlPurposeFooter.SelectedValue)
myDonationDistDataRow("donation_name") = ddlPurposeFooter.SelectedItem.Text
myDonationDistDataRow("donation_value") = Convert.ToDecimal(txtDonationValueFooter.Text)
myDonationDistDataRow("country_code") = Convert.ToInt16(ddlCountryFooter.SelectedValue)
myDonationDistDataRow("country_name") = ddlCountryFooter.SelectedItem.Text
myDonationDistDataRow("distribution_remrks") = txtDonationNotesFooter.Text
myDonationDistDataRow("partial") = chkPartial.Checked
myDonationDistDataRow("standing_inst_num") = If(String.IsNullOrWhiteSpace(standInstruct.Text), 0, Convert.ToInt32(standInstruct.Text))
'add the new DataRow to DataTable's Row
myDonationDistDataTable.Rows.Add(myDonationDistDataRow)
Session("myDonationDistDataTable") = myDonationDistDataTable
grvDonationDist.DataSource = myDonationDistDataTable
grvDonationDist.DataBind()
Catch ex As Exception
'TODO: Log the exception
End Try
End Sub
What is wrong with this code? Am I missing something?
you can't do it that way, you will need to add the event to the update panel
javascript:
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
__doPostBack('<%= UpdatePanel.UniqueId %>', '');
}
}
aspx:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional" onload="UpdatePanel_Load">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
CS:
protected void UpdatePanel_Load(object sender, EventArgs e)
{
//add your code here
}
if you do not get the _doPostBack in your code you can add it like this..
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);
}
I solve it just by add return false after the insertByEnterKey() function
onKeyDown="insertByEnterKey('lbtnAdd'); return false;"
Even better solution:
Make the JavaScript Function return False when the user press "Enter Key" otherwise return True.
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
button.click();
return false;
} else {
return true;
}
}
and use it in the Textbox like this:
<asp:TextBox ID="txtDonationNotesFooter" runat="server" onKeyDown="return insertByEnterKey('lbtnAdd');"></asp:TextBox>

Custom validation javascript function always returns the drop down list's selected value as 0

On my page I have a text box that uses a custom validator:
<asp:CustomValidator ID="cv_Question" ControlToValidate="tb_Question" runat="server" ErrorMessage="*" OnServerValidate="ValidateQuestion" ClientValidationFunction="CheckQuestion" ForeColor="#FF0000" ValidationGroup="CreateUser"></asp:CustomValidator>
The client side validation script that I would like to use always returns 0 for the drop down list SelectedValue, even when the drop down list index has already changed.
I set the drop down list default index to 0 with !Page.IsPostBack
Here is the drop down list:
<asp:DropDownList ID="ddl_Question" runat="server" EnableViewState="true" AutoPostBack="true" onselectedindexchanged="ddl_Question_SelectedIndexChanged">
<asp:ListItem Selected="False" Text="Select a question" Value="0"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was the first movie I ever saw?" Value="1"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is the middle name of my oldest child?" Value="2"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what city was my father born?" Value="3"></asp:ListItem>
<asp:ListItem Selected="False" Text="Who was my favourite cartoon character as a child?" Value="4"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is my mother's middle name?" Value="5"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what year did I meet my significant other?" Value="6"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was my first pet's name?" Value="7"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of the maid of honour at my wedding?" Value="8"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of my best friend in elementary school?" Value="9"></asp:ListItem>
<asp:ListItem Selected="False" Text="Name of my all-time favourite movie character?" Value="10"></asp:ListItem>
<asp:ListItem Selected="False" Text="Create a question" Value="11"></asp:ListItem>
</asp:DropDownList>
Here is the client side validation:
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
<% if(Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{ %>
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
<% }
else
{ %>
alert(<%= Convert.ToInt32(ddl_Question.SelectedValue)%>);
args.IsValid = true;
return;
<% } %>
}
</script>
I only want to validate the tb_Question if the user has selected "Create a question" from the ddl_Question.
EDIT:
Here is my SelectedIndexChanged method. The tb_Question is made visible when the user selects "Create a question". This happens before any validation occurs.
protected void ddl_Question_SelectedIndexChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{
Question.Visible = true;
}
else
{
Question.Visible = false;
}
}
Well my recommendation is to use simple JavaScript
So instead of doing that, use JavaScript and maybe jQuery like this
jQuery Nuget: https://nuget.org/packages/jQuery
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
var questionID = '<%= this.ddl_Question.ClientID %>';
var currentQuestion = $("#" + questionID).val();
if (currentQuestion == '11')
{
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
}
else
{
alert(currentQuestion);
args.IsValid = true;
return;
}
}
</script>
The issue is more likely in the Convert.ToInt32 call since this utility method returns zero when the value passed to it is null (you can check MSDN to validate this. http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) The SelectedValue property is very likely null at this point even though the selected index is zero. Try setting the SelectedValue programmatically and see I that makes any difference.

ASP.NET - Control dropdownlist postback programmatically

I have two dropdownlists on my form-ddl1 and ddl2. They together determine the visibility of a textbox -txt1. For that I do this check:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{txt1.Visible=true;// And then I want to call postback}
}
else
{
if (txt1.Visible)
{txt1.Visible=false;// And then I want to call postback}
}
As you can see, I want to post the page to server only if the above condions are true. The code above is triggered on SelectedIndexChanged event of the both dropdownlists. How can I or is it possible to achieve upon a condition?
I am not sure if i understand your problem but you want to achieve postback only if certain condition is met. you can hook up a javascript function on both dropdown onchange="return onchange();" Set Autopostback = true;
function Onchange() {
var ddl1 = document.getElementById('<%= ddl1.ClientID %>');
var ddl2 = document.getElementById('<%= ddl2.ClientID %>');
var txtbox = document.getElementById('<%= txtbox.ClientID %>');
if (ddl1.selectedIndex == 2 && ddl2.selectedIndex > 2) {
txtbox.style.display = "inline";
__doPostBack(ddl1, '');
}
else {
txtbox.style.display = "none";
return false;
}
}
Aspx code should look like this.
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl1" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl2" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtbox" />
Tested it and it works...
If AutoPostBack = True, which it would have to be for your events to be firing just call a funciton when your condition is met. ASP.NET is always posting back, you just need to handle the condition, otherwise you have to handle the validation with JavaScript and manually post the page:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{
txt1.Visible=true;// And then I want to call postback
//dowork
}
}
else
{
if (txt1.Visible)
{
txt1.Visible=false;// And then I want to call postback
//do work
}
}

Validate TextBox based on DropDownList selection

I need to validate TextBox based on Value selected in DropDownList controls. I have asp:TextBox and asp:DropDownList controls.
If user selects Yes option from the first dropdown he must type value in text box. How can I validate second box? Thanks for help.
The simplest approach is to set the DropDownList's AutoPostBack property to true and handle it's SelectedIndexChanged event. Then you can Enable/Disable the validator there.
Another approach is to use a CustomValidator. This validator is not dependent on a single control. You must write the validation rules on your own. For example the ClientValidationFunction:
<script type="text/javascript" >
function ClientValidate(source, arguments) {
var txt = document.getElementById('TextBox1');
var ddl = document.getElementById('DropDownList1');
var decision = ddl.options[ddl.selectedIndex].text;
if(decision=='Yes'){
arguments.IsValid = txt.value.length > 0;
}else{
arguments.IsValid = true;
}
}
</script>
<asp:DropDownList id="DropDownList1" runat="server">
<asp:ListItem Selected="True">Yes</asp:ListItem>
<asp:ListItem Selected="False">No</asp:ListItem>
</asp:DropDownList>
<asp:TextBox id="TextBox1" runat="server" />
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />
<asp:CustomValidator id="CustomValidator1"
ValidateEmptyText="true"
ControlToValidate="TextBox1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Please enter text!"
runat="server"/>
Remember to always implement a OnServerValidate because you should not rely on javascript only(can be disabled). This is easy:
void ServerValidation(object source, ServerValidateEventArgs args){
args.IsValid = DropDownList1.SelectedIndex == 1 || TextBox1.Text.Length > 0;
}
VB.NET
Protected Sub ServerValidation(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs)
args.IsValid = DropDownList1.SelectedIndex = 1 OrElse TextBox1.Text.Length > 0
End Sub
Add this code to your submit button.
if(DropDownList1.SelectedItem.Text.Equals("Yes") && TextBox1.Text.Length==0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Enter data in the textbox !');", true);
}
Add a CustomValidator control, that validates the TextBox, from there you'll have to do something like this (assuming C#) in the CustomValidator_ServerValidate event handler:
bool valid = false;
if (dropDownList.SelectedValue.Equals("yes")) {
valid = !String.IsNullOrEmpty(textBox.Text);
}
return valid;

Resources