Custom Validator validation not firing for textbox in asp.net - asp.net

<asp:TextBox ID="txtDOB" runat="server" CssClass="textbox_width_height"
placeholder="DD/MM/YYYY" CausesValidation="true"></asp:TextBox>
<asp:CustomValidator id="CustomValidator1" runat="server" Display="Dynamic"
Enabled="true" ValidateEmptyText="true" SetFocusOnError="true"
OnServerValidate="CustomValidator1_OnServerValidate"
ControlToValidate="txtDOB"
ErrorMessage="Age must be grater than 16 years" >
</asp:CustomValidator>
and here is the event
protected void CustomValidator1_OnServerValidate(object source, ServerValidateEventArgs args)
{
DateTime todayDate = System.DateTime.Now;
DateTime textDOB = Convert.ToDateTime(txtDOB.Text);
DateTime total = todayDate.AddYears(-16);
if (textDOB <= total)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}

Place AutopostBack="True" it will become something like this
<asp:TextBox ID="txtDOB" AutoPostBack="true" runat="server" CssClass="textbox_width_height" placeholder="DD/MM/YYYY" CausesValidation="true"></asp:TextBox>
Hope it helps

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

How do i get the value of a datalist item with a button click

I have a dataList with a command button, i want to click the button and obtain the value of a field in the datalist view of the button i have clicked.
I have tried various solutions but keep getting
{"Object reference not set to an instance of an object."}
here is my datalist
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" Width="579px" OnItemCommand = "Datalist1_ItemCommand">
<ItemTemplate>
Epic:
<asp:Label ID="EpicLabel" runat="server" Text='<%# Eval("Epic") %>' />
<br />
ID:
<asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' />
<br />
Company:
<asp:Label ID="CompanyLabel" runat="server" Text='<%# Eval("Company") %>' />
<br />
Date:
<asp:Label ID="DateLabel" runat="server" Text='<%# Eval("Date") %>' />
<br />
time:
<asp:Label ID="timeLabel" runat="server" Text='<%# Eval("time") %>' />
<br />
NewsItem:
<asp:Label ID="NewsItemLabel" runat="server" Text='<%# Eval("NewsItem") %>' />
<br />
HeadLine:
<asp:Label ID="HeadLineLabel" runat="server" Text='<%# Eval("HeadLine") %>' />
<br />
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Epic", "{0}") %>' Text="Button" />
<br />
</ItemTemplate>
</asp:DataList>
and her is my code behind
public void Datalist1_ItemCommand(object sender, DataListCommandEventArgs e)
{
var button = sender as Button;
/// if (button == null) return;
var dataListItem = button.NamingContainer as DataListItem;
if (dataListItem == null) return;
var currentKey = DataList1.DataKeys[dataListItem.ItemIndex];
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
/// if (myLabel == null) return;
var myLabelText = myLabel.Text;
}
You code do this using the following changes on your code;
on your button control:
<asp:Button ID="Button1" runat="server" CommandName="myCommand" Text="Button" />
on your ItemCommand event:
protected void DataList1_ItemCommand(object source,
DataListCommandEventArgs e)
{
switch (e.CommandName)
{
case "myCommand":
// more code could go here
Label myLabel = (Label)e.Item.FindControl("EpicLabel");
var myLabelText = myLabel.Text;
// more code could go here
break;
}
}
If I am not mistaken, the ID of the control you are looking for is actually called EpicLabel, not just Epic. If myLabel is what the debugger is saying is not set to an instance of an object, this is most likely your problem.
So this line:
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "Epic") as Label;
would need to be:
var myLabel = button.Parent.Controls.Cast<Control>().FirstOrDefault(x => x.ID == "EpicLabel") as Label;

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.

custom validator is not working in asp.net

<asp:TextBox ID="TextBox3" runat="server" Width="127px"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox3"
ErrorMessage="Must Be 8 characters"
onservervalidate="CustomValidator1_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="g1">*</asp:CustomValidator>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="LogIn"
ValidationGroup="g1" Width="83px" />
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value.Length == 8)
{
args.IsValid = true;
}
else
args.IsValid = false;
}
I want textbox to take 8 characters.But the event is not getting fired up.I haved tried by taking Required Field Validator as well as ValidateEmptyText to true but either of them is not working
Please Help.
Try adding a RequiredFieldValidator for the TextBox too, and it should trigger the custom validator server validate event.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox3"
ErrorMessage="Required">
</asp:RequiredFieldValidator>

Asp.Net set Visibility of Dropdown list inside gridview in aTemplate Field

I have a Gridview with Template field
<asp:TemplateField HeaderText="Scoring">
<ItemTemplate>
<asp:DropDownList ID="ddlY_N_NA" runat="server"
Visible='<%#Eval("IsTextBox")%>' ></asp:DropDownList>
<asp:TextBox ID="txtAudit" runat="server"
Visible='<%#Eval("IsTextBox")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
I need to set the visibility of drop down based on the visibility of Textbox.
Either of the two has to be shown per row but not both.
Can any help me in this.
Thanks in advance.
Try the following:
<asp:TemplateField HeaderText="Scoring">
<ItemTemplate>
<asp:DropDownList ID="ddlY_N_NA" runat="server"
Visible='<%# ((bool)Eval("IsTextBox")) ? "false" : "true" %>' >
</asp:DropDownList>
<asp:TextBox ID="txtAudit" runat="server"
Visible='<%#Eval("IsTextBox")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
You can do it with the RowDataBound event of the Gridview.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow dr = ((DataRowView)e.Row.DataItem).Row;
if (dr["ColumnName"].ToString()) // your Condition
{
((DropDownList)e.Row.FindControl("dropdownID")).Visible = false;
}
else if (dr["ColumnName"].ToString()) // your Condition
{
((TextBox)e.Row.FindControl("TextboxID")).Visible = false;
}
}
}
Hi, Akram Shahda below is my solution
<asp:TemplateField HeaderText="Scoring" HeaderStyle-Width="12%">
<ItemTemplate>
<asp:DropDownList ID="ddlY_N_NA" Visible='<%#SetVisibility(DataBinder.Eval(Container.DataItem,"IsTextBox"))%>'
runat="server" CssClass="Qdropdown">
</asp:DropDownList>
<asp:TextBox onkeypress="return isNumberKey(event);" ID="txtAudit" Visible='<%#Convert.ToBoolean(Eval("IsTextBox"))%>'
MaxLength="10" runat="server" CssClass="Qinputbox" Width="54px" ValidationGroup="txt"></asp:TextBox>
<asp:HiddenField ID="hdnTextBoxCondition" Value='<%#SetTextBoxVisibility(Eval("IsTextBox"),Eval("TextBoxConditions"))%>'
Visible='<%#Eval("IsTextBox")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
In the code behind I have written the methods which will set the visibility
public bool SetVisibility(object value)
{
if (Convert.ToBoolean(value))
return false;
else
return true;
}
public string SetTextBoxVisibility(object value, object condition)
{
if (Convert.ToBoolean(value))
return Convert.ToString(condition);
else
return "";
}

Resources