Clear Required Field Validation Group - asp.net

I have 14 Fields in my Web page; and for all of them I use RequiredFieldValidator.
This Validator it works fine for all the fields. And when I have an error it caches it and display it to the proper error message area.
In this area I have a button in order to clear the messages and return to the input page.
After I'm caching an error or two I return to the first page by pressing the reset button... correcting the errors... and go forth.
When I'm passing variables to all the fields (which means everything is good) then normally the Validator has to be change and pass the trap (which I have in my code) with no error messages in it...
Here is the trap code...
If Not String.IsNullOrEmpty(RegisterValidationSummary.ValidationGroup) Then
RegisterValidationSummary.Visible = True
ErrorPanel.Visible = True
btnClr.Visible = True
Return
End If
But no the trap works again and return me to the error area without any error displaying.
Only the reset button is there, and the error list is empty.
In order to be sure that all the errors are cleared I use in the reset button the following
Private Sub ClearValidators(sender As Object, e As EventArgs)
RegisterValidationSummary.ValidationGroup = String.Empty
End Sub
At this point the validators are cleared and the trap is not working... The problem is... that happens even when I have certain errors in my page or not.
Thus I use the following code in order to enable the Validators again.
For t = 0 To RegisterValidationSummary.Page.Validators.Count - 1
RegisterValidationSummary.Page.Validators.Item(t).Validate()
Next
Validators are not enabled and of course the trap is not working.
Is someone how knows what is going on and how I may have a certain error erase from validators... and enabled again in order to validate again the fields?

You are doing the validation wrong. First of all ValidationGroup is used to group validations so in a button click you validate the fields in that group. All server controls have this property so that you could group them together for validations by using the same text in this property. Checking the value in this property will not indicate that your values in your controls are valid or not.
So the following condition is always True
If Not String.IsNullOrEmpty(RegisterValidationSummary.ValidationGroup) Then
Therefore, you'll see the reset button all the time.
And, by doing the following you are removing the RegisterValidationSummary control from the ValidationGroup.
RegisterValidationSummary.ValidationGroup = String.Empty
Therefore, after this point you'll not see any error messages since there's no ValidationSummary in the validation group to show the summary of error messages.
Hope I explained why you are seeying what you are seeing right now. Ok, since we know the issue we can easily fix it now.
You should do something like this. Basically we should make use of Page.Validate() and If (Page.IsValid) Then condition to check whether all fields in the ValidationGroup are valid.
Page.Validate()
If (Page.IsValid) Then
' If this condition is true that means all your fields have correct values
Else
' If this condition is true some of your fields are invalid. You can see that in the Validation summary message.
' Not sure why you do the reset but your reset logic could go here
RegisterValidationSummary.Visible = True
ErrorPanel.Visible = True
btnClr.Visible = True
End If
Hope this helps to resolve your issue.

Related

Input field goes blank when Submit is clicked

This is an existing Visual Studio 2003 project (written in VB). There is an input form which contains many fields including a due date field. This field is popultaed based on the value selected in Reason type dropdown and it was also editable. Recently, I had to disable the due date field so that the populated value could not be changed (based on the logged in user). The probelm I am facing is that when the Submit button is clicked, an IE popup window opens and the vlaue in the `due date' field just disappers and becomes blank.
Private Sub btnSubmitOrdersTab_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmitOrdersTab.Click
If Not Me.txtPRCEmail.Value.Length = 0 Or Not hPRCEmail.Value.Length = 0 Then
SubmitClick()
Else
RegisterStartupScript("PRCEmail", "<script language=javascript>window.open (""" & CType(Application("cBaseURL"), String) & "administration/supervisors/Orders/prc_email_reason.aspx"",null,""height=200,width=400,status=yes,toolbar=no,menubar=no,location=no"");</script>")
End If
End Sub
I tried to get the value of the due date just before the RegisterStartupScript() function using duedatevalue = Me.txtDueDate.Value, but it is blank.
Is there any way that I can prevent the due date field from becoming blank. This is not an issue if the due date field is not disabled.
This is the Java Script function I am calling from the onload event of the <body> to disable the due date.
function DisableDueDate()
{
if (udisable == "true")
document.getElementById("divduedate").setAttribute('disabled',true);
else
document.getElementById("divduedate").setAttribute('disabled',false);
}
The reason I used disable is because the due date is in a <td> tag along with a gif next to it (not a server control), which pops up a calender when clicked so that the user can select a date. I want the entire content of the <td> tag disabled- including the gif.
In the btnSubmitOrdersTab_Click event you can save the value of the due date in a Session, and then in the Page_Load you can get the value from the Session and set the due date field with it.
Use readonly instead of using disabling the textbox, if you want to read the value of the texbox on server side.
document.getElementById("divduedate").setAttribute('readonly',true);
OR
document.getElementById("divduedate").readOnly=true
OR
Using jQuery:
$('#readonly').attr("readonly", true)
Disabled attribute will not allow "divduedate" to post its value to the server.
Don't set the Enabled property to False. Instead, use the ReadOnly property and set it to true.

Reading integer from gridview textbox

I am converting a string that is being read from a textbox in gridview
int numTC = Convert.ToInt32(((TextBox)row.FindControl("numTC")).Text);
However it is returning the following exception:
Input string was not in a correct format.
Can anyone see anything wrong in the conversion?
Thanks
Make Sure that your gridview can accept only numbers you can have a filterextender using ajax and I m sure u will do that what else you can do is to check whether you have a textbox is null or not using the Function given below
if(string.IsNullOrEmpty(((TextBox)Row.FindControl("numTC")).Text))
{}
((TextBox)GridViewname.Rows[e.RowIndex].FindControl("numTC")).Text;
and
use this extender or u can use javascript as well
If it is going inside the if statement that means the value is null
if(!string.IsNullOrEmpty(((TextBox)row.FindControl("numTC")).Text)) {}
I have used ! sign now it will go inside the if statement if there is some value in it.
and try to convert this text into integer using try catch block if u get any exception you can take whatever action you want to.
Let me know if it is complete
It is obvious that the value of the returned in the "Text" property of the text box cannot be converted to inter, I guess you have to insure first that you are returning the correct textbox and that it contains a valid value before attempting the conversion.

ASP.Net - validating email address with regexp?

When validating an email address with the regex validation component, an additional RequiredFieldValidator must be added to ensure there is a value present.
I've mostly taken care of this with a CustomFieldValidator, and taking care of this with Javascript.
Is there a better way of doing this?
Why wouldn't you just use the RegularExpressionValidator and the RequiredFieldValidator?
If you use a CustomFieldValidator you will need to implement a javascript check and a server side check as well. Using the other two validation controls together need no extra implementation except for a couple of attributes being set and it is the expected way of doing this type of validation with WebForms.
Consider the next programmer that is going to come along and see your different setup and wonder why you went to all this extra work when none of it was needed.
If you fancy doing it in the background code you could use the following function:
Function checkEMail(ByVal email As String) As Boolean
Dim pattern As String = "^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*""\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|""((?=[\x01-\x7f])[^""\\]|\\[\x01-\x7f])*"")#(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$"
Dim emailCheck As Match = Regex.Match(email, pattern)
If emailCheck.Success Then
checkEMail = True
Else
checkEMail = False
End If
Return checkEMail
End Function

Adding a condition in the url

I would line to add a test condition in an asp.net form such that:
1) From page1.aspx I manually add a query string parameter so that I can trigger the rest of the process in test mode like so: page1.aspx?test=true . This flag must be added in the query string.
2) When I click on a asp.net button in page1.aspx, I am redirected to page2.aspx in test mode
because of teh attached querystring
It seems that I have to work around the postback model of asp.net this is not very straight forward.
Any idea how I can achieve the above behavior?
Thanks
It sounds like you're using a form that posts, but you want to stay in "test" mode. That is, you're not using HTTP-GET so it's not realistic to pass QS variables around.
What I'd do is stash a variable in your Session to set the user's session test mode. So adding &test=true would trigger a Session["TestMode"] = true; before you move to the next page.
Try this (in server-side code)
Response.Redirect("Page2.aspx?Test=" + Request.QueryString["Test"]);

Request.Form sometimes returns the value of a checkbox, other times doesn't

Anyone know what's wrong with this? I have some Classic ASP code that checks for the value of a checkbox, like so:
<!-- HTML page: page1.asp --->
<input id="useBilling" name="useBilling" value="Y" type="checkbox" />
And in my code page (let's call it page2.asp):
' code
useBilling = Request.Form("useBilling")
' useBilling should be "Y" here
If useBilling = "Y" Then
' using billing info
Else
' not using billing info
End If
The problem is that sometimes, even when I check the checkbox, it's passing an empty string to Request.Form and the wrong code is being executed. I've placed a few Response.Write calls to trace it (this is VBScript, remember) and sometimes it says the value is "Y" but later when I check the value in the conditional, it's empty.
Been wracking my brain trying to figure out why the hell this isn't working, because everything seems to be right, just Request.Form sometimes picks up the value and sometimes doesn't, even when it's checked. Hell, sometimes I'll test it by commenting out the execution code and it will say the value is "Y" then when I uncomment the executing code, it's mysteriously empty again.
EDIT: Weirdly enough, if I include a Response.End tag in the conditional, it will operate as I expect, but when I remove the Response.End it no longer finds the checkbox's value (returns empty) even though a minute ago (with Response.End uncommented) it output a test message that says "Okay, the checkbox was checked". With Response.End commented out, it says "The checkbox wasn't checked".
I even try outputting the value of the checkbox (which should be "Y" if it's checked, and nothing if it's not). And, sure enough if the conditional includes Response.End it will output "Y" and if I remove Response.End, it's empty.
Been wracking my brain trying to
figure out why the hell this isn't
working, because everything seems to
be right, just Request.Form sometimes
picks up the value and sometimes
doesn't, even when it's checked.
Not a direct answer, but just to be totally clear: Request.Form("useBilling") will always return an empty value if the checkbox isn't checked. From your "even when I check the checkbox" wording I wasn't quite sure if you were expecting a value there when it wasn't checked. From your code, I think you get it.
As for the issue, I've never seen that happen before despite using ASP for 10+ years (please kill me.) That doesn't mean you're hallucinating, just that I haven't seen it. Interesting!
I wonder if perhaps your HTML (perhaps the form tag in particular) may be malformed. Do you have overlapping tags or a missing closing form tag or anything?
I'd also be extremely curious to see the output of Request.Form when things are misbehaving, ie:
If useBilling = "Y" Then
Response.Write "Cool, it works!"
Else
Response.Write "Something's weird. " & Request.Form
End If
That should be correct, if you submit a form and a checkbox is unchecked its value should be that of an empty string -- if it is checked it should have a value of "on"

Resources