Clear Textbox with Regular Expression Validator - asp.net

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.

Related

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

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.

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.

ASP.NET - Multiple ValidationSummary

Scenario: I am trying to insert a team (composed by multiple persons) on a single page. I have a web user control to insert each person, and when a team has multiple persons several Web User Controls are displayed at the same time.
Each user has a ValidationSummary and several validators (All grouped to the same validation group, example person1 web user control has the validation group on de Validation summary and on each validator set to "valGroup_Person1").
The problem is when validation occurs all errors are grouped and displayed in all web user controls making each web user control display a very long error list. The expected was individual error lists.
Is there a way to get ValidationSummary to perform this way?
If you are using asp.net 2.0 then you must use validation group this will work.
See the below example it will work
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"
ValidationGroup="1">1</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="RequiredFieldValidator2"
ValidationGroup="2">2</asp:RequiredFieldValidator>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
ValidationGroup="1" />
<asp:ValidationSummary ID="ValidationSummary2" runat="server"
ValidationGroup="2" />
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="1" />
<asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="2" />
You have to disambiguate the validation groups from each other by giving them separate names on each of the controls. For example, in the user control's page-init:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
Dim uniqueGroupName = Guid.NewGuid.ToString
valSummary.ValidationGroup = uniqueGroupName
txtFirstName.ValidationGroup = uniqueGroupName
txtLastName.ValidationGroup = uniqueGroupName
btnFind.ValidationGroup = uniqueGroupName
End Sub
(for each control in the group, programmatically give it a validation group)
If you are doing server-side validation, you should call validation for just the group, e.g.
Page.Validate(valSummary.ValidationGroup)
If Not Page.IsValid then Exit Sub
...

Resources