CustomValidator not working (asp.net vb) - asp.net

I am using the CustomValidator for the first time but it doesn't seem to be firing DateExpireRequired_ServerValidate and just runs the code in the Click action.
Been bugging me for a couple hours now! can anyone see a problem with what im doing?
The DropDownList in my code below is populated using Roles.GetAllRoles()
ASP.NET
<asp:Label ID="lUserRole" runat="server" AssociatedControlID="tUserRole">User Role:</asp:Label>
<asp:DropDownList ID="tUserRole" runat="server" CausesValidation="True">
</asp:DropDownList>
<asp:Label ID="lDateExpire" runat="server" AssociatedControlID="tDateExpire">Date Expire:</asp:Label>
<asp:TextBox ID="tDateExpire" runat="server"></asp:TextBox>
<asp:CustomValidator ID="DateExpireRequired" runat="server"
ControlToValidate="tDateExpire" ErrorMessage="Date Expire is required for 'Users'." OnServerValidate="DateExpireRequired_ServerValidate"
ToolTip="Date Expire is required for 'Users'." CssClass="frmError"></asp:CustomValidator>
CODE BEHIND
Sub DateExpireRequired_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs)
If tUserRole.SelectedValue = "User" Then
If tDateExpire.Text <> "" Then
args.IsValid = False
Else
args.IsValid = True
End If
Else
args.IsValid = True
End If
End Sub
Thanks J.

You have Enabled="false" in your custom validator definition. I assume this is disabling that validator.

The answer was as in Menno van den Heuvel's comment above:
Do you have validateemptytext set to True? I see that you check for an empty string in your event handler, but the event handler won't be run if the bound control's value is empty.

Related

How to require checkboxes be checked in vb.net

Can someone please help me figure out how to require more than one checkbox to be checked on my aspx page? I have found a few articles that show how to do this with JavaScript, but I use VB and I am not sure how to apply it.
What I would like to do is once the user clicks the submit button it will display an error if enough checkboxes have not been checked. These are not in a checkbox list but rather individual checkboxes.
You can use a CustomValidator for this purpose.
Within your ASPX page, you put it in your controls and the validator.
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:Label AssociatedControlID="CheckBox1" runat="server">Check this box!</asp:Label>
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:Label AssociatedControlID="CheckBox2" runat="server">And this box!</asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="You must check all of the boxes"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
After this, you can check they click Submit by checking the ServerValidate event.
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
args.IsValid = True ' set default
If Not CheckBox1.Checked Then
args.IsValid = False
End If
If Not CheckBox2.Checked Then
args.IsValid = False
End If
End Sub
The ServerValidateEventArgs will allow you to specify if the user has met your criteria.
At the end of ServerValidate event, it will return the value set in the property IsValid to determine if it's valid or not.

Required field validator doesn´t work

I have this code in my ASPX view:
<asp:TextBox ID="txtDate" runat="server" class="form-control" type="text"></asp:TextBox>
<asp:RequiredFieldValidator id="rfvDate" runat="server" ControlToValidate="txtDate" ErrorMessage="Obligatory field" ViewStateMode="Enabled" CssClass="alert-danger"></asp:RequiredFieldValidator>
</div>
the error message appears correctly when I leave the field empty, but I also want to show an error message when the date is not correctly, I do this in my code behind but it doesn´t work:
Private Sub Mybutton_Click(sender As Object, e As EventArgs) Handles Mybutton.Click
If IsDate(txtDate.Text.ToString) = False Then
rfvDate.IsValid = False
rfvDate.Visible = True
rfvDate.ErrorMessage = "Check that it is a valid date"
Exit Sub
Else
'DO THE REST OF THE CODE
End Sub
What am I doing wrong? thanks
you can use both RequiredField Validator along with RegularExpressionValidator
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtDate" ValidationExpression="(((0|1)[1-9]|2[1-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$"
ErrorMessage="Invalid date format." CssClass="alert-danger" ValidationGroup="Group1" />
Add the ValidationGroup="Group1" to the Button aspx markup

SelectedIndexChange Not Firing

I'm having issue with a dropdownlist updating a textbox, both held within a listview, within an update panel which in turn is in an item template.
Updated
I have got this working with the same code without the above containers in a different web page on the same project, however having trouble linking it with the lisview and other containers.
I am unsure of where the problem lies, the onClick isn't firing unless there's a call back to the server, regardless whether the drop down is contained within the containers mentioned above.
Any help would be greatly appreciated, thanks in advance.
Using asp (1st) and VB code behind (2nd).
<InsertItemTemplate>
<asp:panel runat="server" ChildrenAsTriggers="true" UpdateMode="Always">
<asp:ListView ID="ListView1" runat="server" InsertItemPosition="FirstItem" IAllowPaging="True" EnableViewState="true">
<tr>
<td>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Details")%>' TextMode="MultiLine" />
</td>
<td>
<asp:DropDownList ID="DLL" runat="server" OnSelectedIndexChanged="DLL_SelectedIndexChanged" AutoPostBack="true "EnableViewState="true">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
<asp:ListItem Value="2">No</asp:ListItem>
<asp:ListItem Value="3">Maybe</asp:ListItem>
<asp:ListItem Value="4">I dont know</asp:ListItem>
<asp:ListItem Value="5">Can you repeat</asp:ListItem>
<asp:ListItem Value="6">the question</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</asp:panel>
</InsertItemTemplate>
Code behind
Protected Sub DDL_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim listviewItemThing = DirectCast(sender.parent.NamingContainer, ListViewItem)
Dim tb As TextBox = DirectCast(ddl.NamingContainer.FindControl("TextBox2"), TextBox)
If ddl.SelectedValue = 1 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\1.txt")
ElseIf ddl.SelectedValue = 2 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\2.txt")
ElseIf ddl.SelectedValue = 3 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\3.txt")
ElseIf ddl.SelectedValue = 4 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\4.txt")
ElseIf ddl.SelectedValue = 5 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\5.txt")
ElseIf ddl.SelectedValue = 6 Then
tb.Text = My.Computer.FileSystem.ReadAllText("E:\Users\han\Documents\Templates\6.txt")
Else
tb.Text = ""
End If
End Sub
Update 2
As per request please see attached screen shot of browser console error in debug on VS2013
And expanded error.
Update 3
Added JQuery to try to force PostBack.
function JsFunction() {
__doPostBack('DLL_SelectedIndexChanged', '');
}
ASP link to JQ
<asp:DropDownList ID="DDL" runat="server" Width="120px" OnSelectedIndexChanged="DDL_SelectedIndexChanged" AutoPostBack="true" CausesValidation="false" EnableViewState="true" onchange="javascript:JsFunction()">
You have correct code for your drop down list, so error in other place.
As you see in error message: when you try submit form problem with HtmlEditorExtender.
So just remove or disable it for quick fixing problem.
As for error with HtmlEditorExtender we need a little bit information, of course, if you still need solve it.
Assuming these controls are within the ItemTemplate of your ListView:
FindControl("DDL") won't work, because it's trying to find the control within the page;
ListView1.FindControl("TextBox2") won't work, because there will be multiple instances of TextBox2 within the ListView.
Try this instead:
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim tb As TextBox = DirectCast(ddl.NamingContainer.FindControl("TextBox2"), TextBox)
I assume you haven't got the typo in your actual code:
OnSelectedIndexChanged="DLL_SelectedIndexChanged"
Where the event handler is DDL_SelectedIndexChanged.
Have you put a breakpoint on to check whether the event handler is not being called or if it is bailing out at some point after it fails to do the cast you want it to do?

formview textbox control textchanged event will not fire

I need help in VB (no C# or Javascript, please -- I'm clueless with those languages)
I have also checked all the "questions that may already have your answer -- and those that were in VB didn't match my situation or were resolved by using AutoPostback,coding a textChanged event, or adding ontextchanged= to the textbox field --- I have all of these in my code already.
I can't seem to get the TextChanged event to fire despite setting the AutoPostBack to true.
Even after creating at submit button it still won't fire, what have I left out?
What I'm trying to accomplish:
I want the Finish Date to set to a date 30 days after the Start Date if and only if the user edits a start date.
Otherwise just display in the Finish Date whatever would have originally displayed there.
Both dates are allowed to be null in the database and both are defined as datetime.
In Default.aspx
<asp:FormView ID="FormView1" runat="server" DataKeyNames="MASTERID_Action"
DataSourceID="srcAction">
<EditItemTemplate>
MASTERID_Action:
<asp:Label ID="MASTERID_ActionLabel1" runat="server"
Text='<%# Eval("MASTERID_Action") %>' />
<br />
Action_StartDate:
<asp:TextBox ID="Action_StartDateTextBox" runat="server"
Text='<%# Bind("Action_StartDate") %>'
ontextchanged="Action_StartDateTextBox_TextChanged" AutoPostBack="True" /> <rjs:PopCalendar ID="StartDateCal" runat="server" Control="Action_STartDateTextBox" />
<br />
Action_FinishDate:
<asp:TextBox ID="Action_FinishDateTextBox" runat="server"
Text='<%# Eval("Action_FinishDate") %>' />
<br />
<asp:Button ID="SubmitButton1" runat="server" Text="Refresh"
onclick="SubmitButton1_Click" />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
In Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Action_StartDateTextBox_TextChanged(sender As Object, e As System.EventArgs)
Dim txtStartDate As TextBox = Me.FormView1.FindControl("Action_StartDateTextBox")
Dim txtFinishDate As TextBox = Me.FormView1.FindControl("Action_finishdatetextbox")
Dim strNewFinishDate As String
If txtFinishDate.Text = "" And txtStartDate.Text <> "" Then
strNewFinishDate = Convert.ToString(Convert.ToDateTime(txtStartDate).AddDays(30))
ElseIf txtFinishDate.Text <> "" Then
strNewFinishDate = txtFinishDate.Text
Else
strNewFinishDate = ""
End If
txtFinishDate.Text = strNewFinishDate
End Sub
Protected Sub SubmitButton1_Click(sender As Object, e As System.EventArgs)
Dim mytest As String
End Sub
End Class
16/01/2013 edit: had a typo in Protected Sub Action_StartDateTextBox_TextChanged ran the page but it still doesn't fire. Still need help with this, please.
17/01/2013 edit: My question is still unanswered, the response I did receive caused more errors. Please help.
I think you might have been deleted your controls after writing its corresponding events.If so, as a result it will remove all the handlers that you had specified with the events.
'---This is your code, by the way it seems to be missing its handler
... Action_StartDateTextBox_TextChanged(sender As Object, e As System.EventArgs)
try to add its handler like this,
'---Adding hanler
... Action_StartDateTextBox_TextChanged(sender As Object, e As System.EventArgs) Handles Action_StartDateTextBox.TextChanged
If you need more details regarding Event Handler, Just refer this.
No response on this, but I have to keep moving. So, I have chosen what is probably the smarter route -- to take care of my postbacks as client-side javascript. I would have accepted an answer of "asp.net can't do this. Javascript would make your life so much easier" for this issue....

VB - how to link up a Check_change to code behind for a checkbox

How do I enable a check_change for a checkbox in VB.
Here is what I have so far.
Code Behind:
Protected Sub CheckBoxCash_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxCash.CheckedChanged
Label1.Text = "Cash"
End Sub
Front end code:
<asp:Label ID="Label1" runat="server" Text="Empty"></asp:Label>
<asp:CheckBox ID="CheckBoxPoints" runat="server" Checked="True" />
It looks like you're not doing anything that specifically requires a postback here. In that case, I'd skip the postback entirely an do it more like this:
<asp:Label ID="Label1" runat="server" Text="Empty"></asp:Label>
<asp:CheckBox ID="CheckBoxPoints" runat="server" Checked="True" onclick="document.getElementById('Label1').value = 'Cash';" />
Of course, that's the simple version. Production code would also involve checking the label's clientid property in case these controls ever end up inside a naming container (like an asp:panel or gridview). I'd also look for a fallback for when javascript is not enabled, but in this case the Check_Changed server event depends on javascript to fire anyway.
I figured it out, I forgot to set the postback to true

Resources