Validation not firing in asp.net? - asp.net

<td>Type:
</td>
<td>
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem>---select---</asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
For this dropdownlist, I put validation like this
var ddltype = document.getElementById('<%=ddltype.ClientID%>');
var type = ddltype.options[ddltype.selectedValue].value;
if (type == 0) {
alert("Please Select setter/getter type.");
return false;
}
but it is not firing. How can I write this?

You should really get familiar with ASP.NET validators. Javascript can be disabled.
<asp:DropDownList ID="ddltype" runat="server" AutoPostBack="true">
<asp:ListItem>---select---</asp:ListItem>
<asp:ListItem Text="Setter" Value="1"></asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList><br />
<asp:RequiredFieldValidator ID="reqType" runat="server"
InitialValue="---select---"
ControlToValidate="ddltype"
ErrorMessage="Required: Please select a Type"
Display="Dynamic"
CssClass="blah">
</asp:RequiredFieldValidator>
The InitialValue is important. Otherwise ---select--- would be a valid selection.
Note that i've also added AutoPostBack="true" to the DropDownList, maybe you want to postback immediately as soon as the user has selected an item.
Side-note: use a ValidationSummary with ShowMessageBox="true" and EnableClientScript="true" if you want to show the messages in a javascript alert.

Try this
var ddltype = document.getElementById('<%=ddltype.ClientID%>').text;
if (type == "---select---") {
alert("Please Select setter/getter type.");
return false;
}

Try this way ! but you can use asp.net validation control .
Any way ,my solution will validate two type ,for the dropdown selected vale or dropdown selected item
function Validate()
{
var e = document.getElementById('<%=ddltype.ClientID%>');
//if you need value to be compared then use
var strUser = e.options[e.selectedIndex].value;
//if you need text to be compared then use
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0) **//for text use if(strUser1=="---Select---")**
{
alert("Please Select setter/getter type.");
return false;
}
}
The below code has change your some code and working good for me
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validation() {
debugger;
var e = document.getElementById('<%=ddltype.ClientID%>');
var strUser1 = e.options[e.selectedIndex].value;
if (strUser1 == 0) {
alert("Please Select setter/getter type.");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="validation();" OnClick="btnSave_Click" />
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<div>
</div>
</form>
</body>
</html>
and see this line
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
But you missed set value in that item , So it's get error, Now set value 0 in that line , and now your code working (See my sample code), Or you need to use .text and check the condition for
if(strUser1=="---Select---")
{
//alert
}

Related

Hide and show a dropdownlist based on checkbox selection

So far this is what i have tried and cant get it to work. I had formatted slightly different earlier and the code worked but would only hide/show the the dropdownlist I wanted when i made another selection on my form. I am looking for a way to write this code so that dropdownlist is made visible or non visible as soon as the checkbox changes from false to true and vice versa
<asp:DropDownList ID="ddlcars" runat="server" AutoPostBack="True" Visible="False">
<asp:ListItem>Please select a model</asp:ListItem>
<asp:ListItem Value="18295">Impreza</asp:ListItem>
<asp:ListItem Value="26595">WRX</asp:ListItem>
<asp:ListItem Value="21595">Crosstrek</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlpromocars" runat="server" AutoPostBack="True" Visible="False">
<asp:ListItem>Please select a model</asp:ListItem>
<asp:ListItem Value="25395">BRZ</asp:ListItem>
<asp:ListItem Value="24995">Outback</asp:ListItem>
Spring Promotion
Protected Sub chkpromo_CheckedChanged(sender As Object, e As EventArgs) Handles chkpromo.CheckedChanged
If chkpromo.Checked = True Then
ddlcars.Visible = False & ddlpromocars.Visible = True
Exit Sub
End If
If chkpromo.Checked = False Then
ddlcars.Visible = True & ddlpromocars.Visible False
Exit Sub
End If
End Sub
Remove Autopostback="True" for chkpromo, ddlcars and ddlpromocars to avoid postbacks
Remove Visible="False" for ddlcars and ddlpromocars to write html but hide it with css class.
Remove OnCheckedChanged="chkpromo_CheckedChanged" for chkpromo to avoid postbacks
And try
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>YOUR TITLE</title>
<script type="text/javascript">
function SetDdls(isChecked) {
if (isChecked) {
document.getElementsByName('ddlcars')[0].style.display = 'none';
document.getElementsByName('ddlpromocars')[0].style.display = 'block';
} else {
document.getElementsByName('ddlcars')[0].style.display = 'block';
document.getElementsByName('ddlpromocars')[0].style.display = 'none';
}
}
</script>
<style>
/*only for hide some element */
.hide {
display: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox runat="server" ID="chkpromo" OnClick="SetDdls(this.checked);" Text="Click Me" /> <%--OnClick fires javascript function "SetDdls"--%>
<hr />
<asp:DropDownList ID="ddlcars" runat="server" >
<asp:ListItem>Please select a model</asp:ListItem>
<asp:ListItem Value="18295">Impreza</asp:ListItem>
<asp:ListItem Value="26595">WRX</asp:ListItem>
<asp:ListItem Value="21595">Crosstrek</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlpromocars" runat="server" CssClass="hide"> <%--Hide by default unchecked--%>
<asp:ListItem>Please select a model</asp:ListItem>
<asp:ListItem Value="25395">BRZ</asp:ListItem>
<asp:ListItem Value="24995">Outback</asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
And finally delete from code behind Sub "chkpromo_CheckedChanged".
So i changed my code to this and it works but the dropdownlist wont update until i change another control on my web form. Is there a way that I can make the ddl change upon me clicking on the checkbox
Protected Sub chkPromo_CheckedChanged(sender As Object, e As EventArgs) Handles chkPromo.CheckedChanged
If chkPromo.Checked = True Then
ddlpromocars.visible = True
ddlcars.Visible = False
End If
If chkPromo.Checked = False Then
ddlpromocars.Visible = False
ddlcars.Visible = True
End If
End Sub

Run ASP.Net Custom Validator only on click of one of multiple buttons on the page

I have the following code in my ASP.Net (4.0) page, in which there are 2 buttons - 'Button1' and 'Button2', a textbox, a required field validator and a custom validator.
I would like the custom validator to fire only when 'Button1' clicked and not when 'Button2' is clicked and Button2 still needs to evaluate a required field validator. How would I make this happen?
Input 1:
<asp:TextBox id="txtCustomData" runat="server" />
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
ClientValidationFunction="CheckEven" />
<br/>
Input 2:
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox2"
ErrorMessage="* Required" ForeColor="Red" >
</asp:RequiredFieldValidator>
<br/>
<br/>
<asp:Button id="btn1" runat="server" Text="Button1" />
<br/>
<asp:Button id="btn2" runat="server" Text="Button2" />
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
UPDATE 1:
While Rick's answer is a possible answer, I found another approach to handling this situation.
I can use Validation groups when both buttons need to validate 2 different validators and one of the validators is a custom validator. Set ValidationGroup="Group1" for Button1 that needs to evaluate the custom validator and ValidationGroup="Group2" for Button2 that needs to evaluate the required field validator, and include the same values for corresponding validators. There is no need to include ValidationGroup for the textboxes.
Input 1:
<asp:TextBox id="txtCustomData" runat="server" />
<asp:CustomValidator id="CustomValidator1"
runat="server" ErrorMessage="Number not divisible by 2!"
ControlToValidate="txtCustomData"
ClientValidationFunction="CheckEven" />
<br/>
Input 2:
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox2"
ErrorMessage="* Required" ForeColor="Red" ValidationGroup="Group2">
</asp:RequiredFieldValidator>
<br/>
<br/>
<asp:Button id="btn1" runat="server" Text="Button1" ValidationGroup="Group1"/>
<br/>
<asp:Button id="btn2" runat="server" Text="Button2" ValidationGroup="Group2"/>
<script language="javascript">
<!--
function CheckEven(source, args) {
var val = parseInt(args.Value, 10);
if (isNaN(val)) {
args.IsValid = false;
}
else {
args.IsValid = ((val % 2) == 0);
}
}
// -->
</script>
UPDATE 2:
If you end up using custom javascript in OnClientClick event of the button, then you need to be careful with your javascript else you might end up having your button never postback even when data is valid.
For example if you have written a custom javascript function called 'ValidateData( )' then first make sure that it always has return true or return false statement in it, and second your OnClientClick should use this function in the manner shown below. Most developers will simply use OnClientClick = "return ValidateData();" which will make the ASP.Net button to NEVER perform an ASP.Net post back even when the data is evaluated as valid, since the default __doPostBack JavaScript function in ASP.Net will never get called (assuming UseSubmitBehavior="false" for this button, if UseSubmitBehavior="true" then __doPostBack is not used and button will postback).
<asp:Button id="btn1" runat="server" Text ="Button1"
OnClientClick="var r = ValidateData(); if (!r) { return false; } " />
<script type=<script type="text/javascript">
function ValidateData( )
{
var x = document.getElementById('xy1');
if(x.value == '1')
{
return false;
}
return true;
}
</script>
Include the CausesValidation attribute and set it to False. Your button will not trigger validation.
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation(v=vs.110).aspx
<asp:Button id="btn2" runat="server" Text="Button2" CausesValidation="False"/>

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
}
}

how to enable asp.net checkboxlist from javascript?

I am trying to enable my checkboxlist from js? this is my code sofar:
html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script>
function enabledCBL() {
document.getelementbyid('CheckBoxList1').disabled = false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<button onclick="enabledCBL()">enable</button>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" TextAlign="Right">
<asp:ListItem Text="een">
</asp:ListItem>
<asp:ListItem Text="twee">
</asp:ListItem>
<asp:ListItem Text="drie">
</asp:ListItem>
<asp:ListItem Text="vier">
</asp:ListItem>
</asp:CheckBoxList>
</div>
</form>
</body>
</html>
Please set your CheckBoxList with ClientIDMode="Static" then try again. If not specify ClientIDMode it will generate some id like ct001_CheckBoxList
Read more:
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
JavaScript is case-sensitive. Your statement must be:
document.getElementById('CheckBoxList1').disabled = false;
Try,
function enabledCBL() {
var tab = document.getElementById('CheckBoxList1');
var checkboxes = tab.getElementsByTagName("input");
for (i = 0; i < checkboxes.length; i++)
checkboxes[i].disabled = false;
}
The <button> tag does postback you need to add type attribute to the button.
<button type="button" onclick="enabledCBL()">
enable</button>
Uncheck the items in checkboxlist But i have tired the enable checklist in javascript..But its not working for me..Hope this code will help you . So for I posted here.
function Validate()
{
var tableBody = document.getElementById('CheckBoxList1').childNodes[0];
for (var i=0;i<tableBody.childNodes.length; i++)
{
var currentTd = tableBody.childNodes[i].childNodes[0];
var listControl = currentTd.childNodes[0];
if (listControl.checked==true)
{
listControl.checked = false;
}
}
}
<asp:CheckBoxList ID="CheckBoxList1" runat="server" TextAlign="Right">
<asp:ListItem Text="aa">
</asp:ListItem>
<asp:ListItem Text="twee">
</asp:ListItem>
<asp:ListItem Text="drie">
</asp:ListItem>
<asp:ListItem Text="vier">
</asp:ListItem>
</asp:CheckBoxList>
I have seen an Example based on your needs in Jquery Refer this link Jquery

Dropdown selection navigation to different page with dropdown values; Asp.Net + Javascript

I want to access drop down menu's variable in java script on change event, here is my code
<asp:DropDownList ID="DropDownList1" runat="server" onchange="document.location.href = url_Lookbook;" >
<asp:ListItem Value="0">hello</asp:ListItem>
<asp:ListItem Value="1">world</asp:ListItem>
</asp:DropDownList>
here is the script coding:
<script type="text/javascript">
var url_Lookbook = "http://microsoft.com";
</script>
My question is how do I pass down value=0 or value = 1 to different page, any help is appreciated.
If you wrote it as a javascript function, it would be simpler
<asp:DropDownList ID="DropDownList1" runat="server" onchange="navFromList(this.value);" >
<asp:ListItem Value="0">hello</asp:ListItem>
<asp:ListItem Value="1">world</asp:ListItem>
</asp:DropDownList>
<script type="text/javascript">
function navFromList( qsParam )
{
document.location.href = "http://microsoft.com?arg=" + qsParam;
return false;
}
</script>
This is how I do it, completely in server side code. You don't have to use javascript (if you aren't required to)
<asp:DropDownList ID="ddlGlobalDestinations" runat="server" OnSelectedIndexChanged="ddlGlobalDestinations_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="StackOverflow" Value="http://www.stackoverflow.com"></asp:ListItem>
<asp:ListItem Text="Google" Value="http://www.google.com/"></asp:ListItem>
<asp:ListItem Text="Microsoft" Value="http://www.microsoft.com/"></asp:ListItem>
</asp:DropDownList>
here is the c# code-behind
protected void ddlGlobalDestinations_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect(ddlGlobalDestinations.SelectedValue, true);
}
onchange="document.location.href = url_Lookbook + '?param=' + this.value;" appears to work in FF3 and IE7.

Resources