Required field validator doesn´t work - asp.net

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

Related

Not able to disable Required Field Validator in VB.NET

I have a required field validator for a textbox which I want to disable on click of a link button. I coded like so.
Protected Sub lnkDeleteTimeSlots_click(sender As Object, e As EventArgs)
txtTimeslotName_RequiredFieldValidator.Enabled = False
End Sub
The design of the textbox.
<asp:TextBox ID="txtTimeslotName" runat="server"></asp:TextBox>
<font color="red">*</font>
<asp:RequiredFieldValidator ID="txtTimeslotName_RequiredFieldValidator"
runat="server"
ErrorMessage="Timeslot Name Required!"
Display="None"
ControlToValidate="txtTimeslotName"
ForeColor="Red"
ValidationGroup="Timetable">
</asp:RequiredFieldValidator>
But it still validates for the required field. What is the issue?
EDIT:
The linkbutton is inside a grid. When it is clicked, I open a popup window with the textbox and a button. The code for the button is like so.
<asp:Button ID="btnMAdd" runat="server" Text="Add Timeslot" PostBackUrl="~/TimeSlots.aspx" OnClick="btnMAdd_Click" CssClass="button" ValidationGroup="Timetable" OnClientClick="javascript:shouldsubmit=true;" />
Set Cause Vlaidation Property of Link Button to falselike this...
CausesValidation="false" so it will allow you to call your code and disable your Validator...
I have fixed this issue - removed the CausesValidation from the linkbutton.

Clear Textbox with Regular Expression Validator

I Got a text box with a Regular Expression validator, to validate if my textbox is numeric.
here's the code :
<asp:TextBox ID="txtAmount" runat="server" CssClass="TextBoxCls"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="valNumbersOnly" ControlToValidate="txtAmount"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box."
Font-Bold="true" ForeColor="Red" ValidationExpression="(^([0-9 ]*|\d*\d{1}?\d*)$)">
</asp:RegularExpressionValidator>
and , if the user accidentally input the wrong data , it'll show the Error Like This :
and i give the user, a clear function to clear all the textbox : with kind of this function :
Public Sub ClearTextBox(ByVal root As Control)
For Each ctrl As Control In root.Controls
ClearTextBox(ctrl)
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Text = String.Empty
End If
Next ctrl
End Sub
Protected Sub btnClr_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClr.Click
ClearTextBox(Me)
dropResponse.SelectedIndex = 0
FillData()
End Sub
but , the amount is not cleared, it still show the error. why it still happen?
If you are providing this through another button on the same form it won't ever hit the code-behind.
If you want a button on a validated form that needs to fire regardless of whether the other controls have validated, put it in a separate validation group:
<asp:Button runat="server" ID="btnClr" Text="Clear form" OnClick="btnClr_Click" ValidationGroup="unvalidatedControls" />
Alternatively, put a validation group on your controls that need validating and also the button that submits the form:
<asp:TextBox ID="txtAmount" runat="server" CssClass="TextBoxCls" ValidationGroup="validatedControls"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="valNumbersOnly" ControlToValidate="txtAmount"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box."
Font-Bold="true" ForeColor="Red" ValidationExpression="(^([0-9 ]*|\d*\d{1}?\d*)$)"
ValidationGroup="validatedControls">
</asp:RegularExpressionValidator>
<asp:Button runat="server" ID="btnSubmit" Text="Submit Form" ValidationGroup="validatedControls" />
You could put a ValidationGroup attribute on both your clear button and the main form, as long as they're different, the clear button will work just fine.
Some documentation on Validation Groups: http://msdn.microsoft.com/en-us/library/ms227424.aspx
I suspect that the textbox is contained in a panel or another container control. Only the toplevel controls of a page are available in the controls collection of the page.
I would suggest to change the parameter of the call to ClearTextBox with the correct container control.

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

Enabling/Disabling RegularExpressionValidator in code behind

I have a problem with RegularExpressionValidator connected with TextBox:
<asp:TextBox ID="tbPRCOD" runat="server" Font-Bold="True" ForeColor="Green" BackColor="White" BorderStyle="None" Width="50%"></asp:TextBox>
<asp:RegularExpressionValidator id="revPRCOD" runat="server" SetFocusOnError="True"
ErrorMessage="<%$ Resources:GlobalTranslations, max20char %>" Display="Dynamic"
ControlToValidate="tbPRCOD" BackColor="Transparent" Font-Bold="True"
Font-Underline="True" ForeColor="Red" ValidationExpression="^[a-zA-Z0-9]{0,20}$">
On page I have Drop down list:
<asp:DropDownList ID="cmbIDFAM" runat="server" Width="98%" SkinID="mandatoryCombo" Font-Size="X-Small" AutoPostBack="true" > </asp:DropDownList></td>
At start validator is enabled (if string in text box will be over 20 characeters then validator shows validate error). If I change selected item in DropDownList to item with value 5 then I want to turn off validation because for this index in DropDownList, I want to write in TextBox (tbPRCOD) more than 20 characters:
Protected Sub cmbIDFAM_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbIDFAM.SelectedIndexChanged
If getValueFromCombo(cmbIDFAM) = 5 Then
tbPRCOD.MaxLength = 100
revPRCOD.Enabled = False
Else
tbPRCOD.MaxLength = 20
revPRCOD.Enabled = True
End If
End Sub
Everything works fine until I change cmbIDFAM DropDownList to 5th item. I put in TextBox more than 20 characters, and now RegularExpressionValidator is disabled so it don't show error in validate. When I change item in ddl then in TextBox is more than 20 characters and validator is enabled, but error doesn't show in page. Why? How to force validation? I also use function to force Validation, after change item in ddl:
revPRCOD.Validate()
This won't help in this situation. Thanks for Help.
Mat.

how to change the label text if date displayed in textbox2 is greater than textbox1?

I have textbox in my asp.net 3.5 VB.net webform
in my textbox1 the text is : 30-Dec-2010, 06:00:00 PM
i want when the date in textbox is greater than textbox1 then the Label text would be "No REfund ! Sorry"
How to do this
You should use ASP.Net CompareValidator for this purpose. You can check both on client- and serverside. Besides i would recommend not to have Date AND Time in one Textbox. That makes it more difficult to validate and it's not standard, so it might be confusing and error-phrone for users.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1" ControlToValidate="TextBox2" Type="Date" Operator="GreaterThan" runat="server" ErrorMessage="No REfund ! Sorry" EnableClientScript="true" ></asp:CompareValidator>
<asp:Button ID="BtnPostback" runat="server" Text="postback" />
On the serverside you should also trigger the validation(f.e. if javascript is disabled):
Private Sub BtnPostback_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnPostback.Click
Page.Validate()
If Me.IsValid Then
'Do something f.e. save'
End If
End Sub
CompareValidator Class
It would be better if you do it using javascript because this functionality does not require postback. A similar question has been posted on stackoverflow which compares two dates using javascript. Check it out here. You just need to extend it to incorporate assigning text to the label.

Resources