I am currently working with a small class that uses Javascript to display alerts. The situation is this: I have implemented this class on a page where users must input valid zip codes. If an invalid zip code is entered, an alert is shown and the user is redirected back to correct it. However, if a valid zip code is entered, they are redirected to another page. The issue arises when users click the back button on their browser; the alert is displayed regardless of the validity of the zip code.
Here is the sequence:
Zip entry page -> Enter Zip -> Check Zip
If a valid zip is entered, go to overview.aspx. If not, return to the zip entry page.
On overview.aspx
, if the user clicks the back button, the alert pops up. This behavior is not desired. Below is the well-functioning code for the alert class, followed by the code that checks and displays the alert upon clicking the LinkButton.
protected void GotoReview(object sender, EventArgs e) {
if (ValidateZipCode(ZipCode)) {
Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
ProductCode, ZipCode));
}
else {
Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
}
}
private bool ValidateZipCode(string zip) {
if (zip.Length < 5 || zip.Length > 5) {
return false;
}
if (!Regex.IsMatch(zip, @"^(\d{5}-\d{4})|(\d{5})$")) {
return false;
}
return true;
}
public static class Alert {
public static void Show(string message) {
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) {
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}