Validation stops working with hidden divs - c#

I have created my own CRM system which works perfectly locally. However, when the project has been uploaded to our web server, I'm getting some weird errors. I'm hoping the one I'm describing here is the catalyst for the others.
There is a section that shows the next lead to call with a button to click so you can amend the lead contact details. It's a basic hide/show div toggle. I have validation on the textboxes in the "amendtext" div. However, the validation is completely ignored on the button click (I'm using a validation group). Remove the hide/show on the divs and the validation works fine.
Here's the code I'm using to arrange the divs and call the click to save event. I've edited out all the styling etc:
<div>
<div id="viewtext" runat="server">
<div class="leadaddress">
<p><strong><asp:Label ID="lblName" runat="server" Text=""></asp:Label></strong></p>
<p><asp:Label ID="lblAddress" runat="server" Text=""></asp:Label><br /></p>
</div>
<div>
<p><asp:Label ID="lblLeadTel" runat="server" Text=""></asp:Label></p>
</div>
<div class="leaddetailsbut">
<p><asp:LinkButton ID="clickToAmend" runat="server" OnClick="clickToAmend_Click">Amend Address</asp:LinkButton></p>
</div>
</div>
<div id="amendtext" runat="server">
<p>
<label>Company</label>
<asp:TextBox ID="tbLeadName" runat="server" ></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorLeadName" runat="server"
ControlToValidate="tbLeadName"
OnServerValidate="CustomValidatorLeadName_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="Lead">
</asp:CustomValidator>
</p>
<p>
<label class="lblwidth80">Address 1</label>
<asp:TextBox ID="tbAddress1" runat="server" ></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorLeadAddress1" runat="server"
ControlToValidate="tbAddress1"
OnServerValidate="CustomValidatorAddress1_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="Lead">
</asp:CustomValidator>
</p>
<p>
<label class="lblwidth80">Address 2</label>
<asp:TextBox ID="tbAddress2" runat="server" ></asp:TextBox>
</p>
<p>
<label class="lblwidth80">City</label>
<asp:TextBox ID="tbCity" runat="server" ></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorCity" runat="server"
ControlToValidate="tbCity"
OnServerValidate="CustomValidatorCity_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="Lead">
</asp:CustomValidator>
<label>Postcode</label>
<asp:TextBox ID="tbPostcode" runat="server" ></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorPostcode" runat="server"
ControlToValidate="tbPostcode"
OnServerValidate="CustomValidatorPostcode_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="Lead">
</asp:CustomValidator>
</p>
<div>
<p>
<label>Telephone</label>
<asp:TextBox ID="tbTelephone" runat="server" ></asp:TextBox>
<asp:CustomValidator
ID="CustomValidatorTelephone" runat="server"
ControlToValidate="tbTelephone"
OnServerValidate="CustomValidatorTelephone_ServerValidate"
ValidateEmptyText="True"
ValidationGroup="Lead">
</asp:CustomValidator>
</p>
</div>
<div>
<asp:LinkButton ID="clickToSave" runat="server" OnClick="clickToSave_Click" ValidationGroup="Lead">Save Address</asp:LinkButton>
</div>
</div>
</div>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
viewtext.Visible = true;
amendtext.Visible = false;
}
protected void clickToAmend_Click(object sender, EventArgs e)
{
viewtext.Visible = false;
amendtext.Visible = true;
}
protected void clcikToSave_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
//code to save the change...
viewtext.Visible = true;
amendtext.Visible = false;
}
}
I'm now starting to pull what little hair I have left...

Related

AsyncFileUpload in Repeater in UpdatePanel

The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.
<asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
<ContentTemplate>
<div class="field-group list-of-resource">
<asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
<ItemTemplate>
<div class="resource">
<div class="remove-input">
<asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
<span>Remove</span>
</div>
<h2>Details of Resources
<span class="counter">
<asp:Literal ID="LitCount" runat="server"></asp:Literal>
</span>
</h2>
<ul>
<li>
<fieldset class="form-group">
<legend>Accession No.</legend>
<asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Details</legend>
<asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
<li>
<fieldset class="form-group">
<legend>Image</legend>
<ajaxToolkit:AsyncFileUpload runat="server"
ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
<asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
</fieldset>
</li>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="add-input">
<asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
<span>Add another request</span>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
</Triggers>
</asp:UpdatePanel>
First add command name to linkbutton and remove click event:
<asp:LinkButton ID="LbAddRequest" runat="server"
CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>
And try this ItemCommand event in code-behind to get in work:
protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRequest")
{
FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
if (myFileUpload.HasFile)
{
try
{
string filename = Path.GetFileName(myFileUpload.FileName);
myFileUpload.SaveAs(Server.MapPath("~/") + filename);
myStatusLabel.Text = "Upload Success";
}
catch (Exception ex)
{
myStatusLabel.Text = "Upload Fail" + ex.Message;
}
}
else
{
myStatusLabel.Text = "myFileUpload Has No File";
}
}
}
Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File

null reference exception on page redirect

I'm getting a null reference exception on singleKingButton.Checked = true; in the page load event. If I comment it out then I still get one on the next line setting the date. The odd thing is the page loads fine it's when I hit the submit button that I get the error. Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace garrettPenfieldUnit4
{
public partial class Default : System.Web.UI.Page
{
Reservation newReservation = new Reservation();
//Load events, automatically inserts todays date and selects the single king radio button
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
singleKingButton.Checked = true;
arrivalDateBox.Text = DateTime.Today.ToShortDateString();
}
//When submit button is clicked show the two confirmation labels.
protected void submitButton_Click(object sender, EventArgs e)
{
newReservation.ArrivalDate = Convert.ToDateTime(arrivalDateBox.Text);
newReservation.DepartureDate = Convert.ToDateTime(departureDateBox.Text);
newReservation.NoOfPeople = peopleDropDown.SelectedIndex;
newReservation.SpecialRequests = specialRequestsBox.Text;
newReservation.FirstName = firstNameBox.Text;
newReservation.LastName = lastNameBox.Text;
newReservation.Email = addressBox.Text;
newReservation.Phone = telephoneNumberBox.Text;
newReservation.PreferredMethod = contactDropDown.SelectedIndex.ToString();
if (singleKingButton.Checked)
{
newReservation.BedType = "Single King";
}
if (twoQueensButton.Checked)
{
newReservation.BedType = "Two Queens";
}
if (singleQueenButton.Checked)
{
newReservation.BedType = "Single Queen";
}
Session["Reservation"] = newReservation;
Response.Redirect("~/ConfirmationPage.aspx");
}
//When the clear button is clicked clear the form and reset fields to their default values
protected void clearButton_Click(object sender, EventArgs e)
{
arrivalDateBox.Text = DateTime.Today.ToShortDateString();
departureDateBox.Text = String.Empty;
peopleDropDown.SelectedIndex = 0;
singleKingButton.Checked = true;
twoQueensButton.Checked = false;
singleQueenButton.Checked = false;
specialRequestsBox.Text = String.Empty;
firstNameBox.Text = String.Empty;
lastNameBox.Text = String.Empty;
addressBox.Text = String.Empty;
telephoneNumberBox.Text = String.Empty;
contactDropDown.SelectedIndex = 0;
}
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="garrettPenfieldUnit4.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Royal Inn and Suites</title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<link href="Content/Main.css" rel="stylesheet" />
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</head>
<body>
<form id="form1" runat="server" defaultbutton="submitButton" defaultfocus="arrivalDateBox">
<div class="container">
<div id="page-header">
<h1 style="color: blue;">Royal Inn and Suites</h1>
<p style="color: red; font-style: italic;">
Where you're always treated like royalty
</div>
<h3 style="color: blue;">Reservation Request</h3>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ForeColor="Red" />
</div>
<div id="form-group">
<h4>Request Data</h4>
<div>
Arrival Date<asp:RequiredFieldValidator ID="arrivalDateBoxValidator" runat="server" ErrorMessage="Arrival date is required"
ControlToValidate="arrivalDateBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="arrivalDateValidator" runat="server" ErrorMessage="Arrival date must be before departure date."
ControlToValidate="arrivalDateBox" ControlToCompare="departureDateBox" Display="Dynamic"
Operator="DataTypeCheck" Type="Date" ForeColor="red">*</asp:CompareValidator>
</div>
<div>
<asp:TextBox ID="arrivalDateBox" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div>Departure Date</div>
<div>
<asp:TextBox ID="departureDateBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="departureDateBoxValidator" runat="server" ErrorMessage="Departure date is required"
ControlToValidate="departureDateBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="departureDateCompareValidator" runat="server" ErrorMessage="Departure date must be after arrival date"
ControlToValidate="departureDateBox" ForeColor="Red" ControlToCompare="arrivalDateBox" Display="Dynamic" Operator="GreaterThan"
Type="Date">*</asp:CompareValidator>
</div>
<div>Number of People</div>
<div>
<asp:DropDownList ID="peopleDropDown" runat="server" CssClass="form-control">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<div>
Bed Type
<asp:RadioButton ID="singleKingButton" runat="server" Text="King" GroupName="bedType" />
<asp:RadioButton ID="twoQueensButton" runat="server" Text="Two Queens" GroupName="bedType" />
<asp:RadioButton ID="singleQueenButton" runat="server" Text="Single Queen" GroupName="bedType" />
</div>
</div>
<h3>Special Requests</h3>
<div>
<asp:TextBox ID="specialRequestsBox" runat="server" TextMode="MultiLine" CssClass="form-control"></asp:TextBox>
</div>
<h3>Contact Information</h3>
<div>First Name</div>
<asp:TextBox ID="firstNameBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="firstNameBoxValidator" runat="server" ErrorMessage="First name is required"
ControlToValidate="firstNameBox" ForeColor="Red">*</asp:RequiredFieldValidator>
<div>Last Name</div>
<asp:TextBox ID="lastNameBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="lastNameBoxValidator" runat="server" ErrorMessage="Last name is required"
ControlToValidate="lastNameBox" ForeColor="Red">*</asp:RequiredFieldValidator>
<div>E-mail Address</div>
<asp:TextBox ID="addressBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="addressBoxValidator" runat="server" ErrorMessage="Email address is required"
ControlToValidate="addressBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="addressBoxExpressionValidator1" runat="server" ErrorMessage="Invalid Email"
ControlToValidate="addressBox" ForeColor="Red" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
<div>Telephone Number</div>
<asp:TextBox ID="telephoneNumberBox" runat="server" CssClass="form-control"></asp:TextBox>
<asp:RequiredFieldValidator ID="telephoneNumberBoxValidator" runat="server" ErrorMessage="Telephone Number is required"
ControlToValidate="telephoneNumberBox" ForeColor="Red" Display="Dynamic">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="telephoneExpressionValidator" runat="server"
ErrorMessage="Invalid phone number" ControlToValidate="telephoneNumberBox" ForeColor="red" Display="Dynamic" ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}">*</asp:RegularExpressionValidator>
<div>Preferred Method of Contact</div>
<asp:DropDownList ID="contactDropDown" runat="server" CssClass="form-control">
<asp:ListItem>E-mail</asp:ListItem>
<asp:ListItem>Telephone</asp:ListItem>
</asp:DropDownList>
<div>
<asp:Button ID="submitButton" class="btn btn-primary btn-space" runat="server" Text="Submit" OnClick="submitButton_Click" />
<asp:Button ID="clearButton" class="btn btn-primary btn-space" runat="server" Text="Clear" OnClick="clearButton_Click" BackColor="#33CC33" />
</div>
<div>
<asp:Label ID="submitLabel1" runat="server" Text="Thank you for your Request." Visible="False" ForeColor="Green"></asp:Label>
</div>
<div>
<asp:Label ID="submitLabel2" runat="server" EnableViewState="False" Text="We will get back to you within 24 hours." Visible="False" ForeColor="Green"></asp:Label>
</div>
</div>
</form>
</body>
</html>
One of these all properties is receiving 'NULL' and at the time of inserting this values in database your table structure is not allowing 'NULL'.
So make sure that if you want to store 'NULL' in table then allow NULL in table structure (Table design).
You can check it using "line by line execution" of your code (using break point).

asp button doesn't invoke postback in usercontrol updatepanel

I have two asp buttons in my user control inside an update panel. But when I click them the postback is not completed (I have a java script alert set to page_load to tell me when a post back occurs, for example, it fires when the dropdownlist selection is changed). I can't figure out why the buttons are not posting back.
My usercontrol, the buttons in question are createBtn and signinBtn.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Login.ascx.cs" Inherits="TestApp2.Views.Login" %>
<asp:UpdatePanel ID="LoginMainUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:TextBox ID="infoTB" runat="server" TextMode="MultiLine" />
<div>
<div class="left-align" style="background-color:blue">
<asp:button runat="server" id="createBtn" CssClass="btn btn-default" OnClick="createBtn_Click" Text="Create" /><br/>
<asp:button runat="server" id="signinBtn" CssClass="btn btn-default" OnClick="signinBtn_Click" Text="Sign In" />
</div>
<!-- Login View -->
<div id="loginView" runat="server" class="centre-form centering text-center" style="background-color:green">
<h1>Login</h1>
<asp:Label ID="info" runat="server" Text="" />
<div class="form-group">
<label for="userIn">Username</label>
<asp:TextBox runat="server" id="userIn" CssClass="form-control" TextMode="SingleLine" />
<asp:RequiredFieldValidator runat="server" id="reqUser" controltovalidate="userIn" errormessage="Enter Username" />
</div>
<div class="form-group">
<label for="passwordIn">Password</label>
<asp:TextBox runat="server" id="passwordIn" CssClass="form-control" Text="Enter Password" TextMode="Password" />
<asp:RequiredFieldValidator runat="server" id="reqPass" controltovalidate="passwordIn" errormessage="Enter Password" />
</div>
<asp:Button runat="server" id="loginBtn" CssClass="btn btn-default" onclick="loginBtn_Click" text="Login" />
</div>
<!-- Create Account View -->
<div id="createView" runat="server" class="centre-form centering text-center" style="background-color:green">
<h1>Create</h1>
<div class="form-horizontal">
<div class="form-group" style="background-color:yellow;">
<asp:TextBox runat="server" id="personalFName" CssClass="form-control" TextMode="SingleLine" />
<label class="control-label" for="personalFName">First Name</label>
</div>
<div class="form-group">
<asp:TextBox runat="server" id="personalLName" CssClass="form-control" TextMode="SingleLine" />
<label class="control-label" for="personalLName" >Last Name</label>
</div>
<div class="form-group">
<asp:DropDownList runat="server" id="selGender" CssClass="form-control">
<asp:ListItem Value="Male" Text="Male" />
<asp:ListItem Value="Female" Text="Female" />
<asp:ListItem Value="Other" Text="Other" />
</asp:DropDownList>
<label class="control-label" for="selGender">Gender</label>
</div>
<asp:UpdatePanel ID="dobUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<div class="form-group">
<asp:DropDownList runat="server" id="selYear" CssClass="form-control" OnSelectedIndexChanged="selYear_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList runat="server" id="selMonth" CssClass="form-control" OnSelectedIndexChanged="selMonth_SelectedIndexChanged" AutoPostBack="true" />
<asp:DropDownList runat="server" id="selDay" CssClass="form-control"/>
<label class="control-label" for="selDay" >Date of Birth</label>
</div>
</COntentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
The code behind is as so
public partial class Login : System.Web.UI.UserControl
{
private DateMenu dobCtrl;
protected void Page_Load(object sender, EventArgs e)
{
if (Session[Paths.USERDETAILS] != null) Response.Redirect(Paths.USERCTRL_BASE + "Profile.ascx");
else setDetails();
}
protected void loginBtn_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
String SOAPbdy = "<Username>" + userIn.Text + "</Username><Password>" + passwordIn.Text + "</Password>";
HTTPRequest req = new HTTPRequest();
String response = req.HttpSOAPRequest(SOAPbdy, "GetUser");
infoTB.Text += response;
String uIDs = (new XMLParse(response)).getElementText("UserID");
int uID = 0;
Int32.TryParse(uIDs, out uID);
if (uID > 0)
{
Session["userDetails"] = response;
info.Text = "Success";
}
else info.Text = "Login failed";
}
}
private void setDetails()
{
if (dobCtrl == null) dobCtrl = new DateMenu(selYear, selMonth, selDay);
dobCtrl.setDateDropdown();
}
protected void UpdatePanel_Unload(object sender, EventArgs e)
{
MethodInfo methodInfo = typeof(ScriptManager).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.Where(i => i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First();
methodInfo.Invoke(ScriptManager.GetCurrent(Page),
new object[] { sender as UpdatePanel });
}
protected void selYear_SelectedIndexChanged(object sender, EventArgs e)
{
dobCtrl.fillDays();
}
protected void selMonth_SelectedIndexChanged(object sender, EventArgs e)
{
dobCtrl.fillDays();
}
protected void createBtn_Click(object sender, EventArgs e)
{
loginView.Visible = false;
}
protected void signinBtn_Click(object sender, EventArgs e)
{
}
}
I believe you have to register the controls for postback using
ScriptManager.RegisterPostbackControl()
https://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerpostbackcontrol%28v=vs.110%29.aspx
Try setting up the triggers for the UpdatePanel like so:
<asp:UpdatePanel ID="LoginMainUpdatePanel" runat="server" UpdateMode="Conditional" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<asp:TextBox ID="infoTB" runat="server" TextMode="MultiLine" />
<div>
<div class="left-align" style="background-color:blue">
<asp:button runat="server" id="createBtn" CssClass="btn btn-default" OnClick="createBtn_Click" Text="Create" /><br/>
<asp:button runat="server" id="signinBtn" CssClass="btn btn-default" OnClick="signinBtn_Click" Text="Sign In" />
</div>
[...]
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="createBtn" />
<asp:PostBackTrigger ControlID="signinBtn" />
</Triggers>
</asp:UpdatePanel>
Try adding PostBackTriggers for the UpdatePanel.
Add 2 triggers one for each of the buttons.
<asp:UpdatePanel ID="myUpdatePanel" runat="server" UpdateMode="Conditional"ChildrenAsTriggers="false">
<ContentTemplate>
//Your Content
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="createBtn" />
<asp:PostBackTrigger ControlID="Signbtn" />
</Triggers>
</asp:UpdatePanel>
It was because of the asp form validation, no postback (async or not) was occurring because the form wasn't valid. Removing that made it all work.

Form not rendering updated label after postback

I have been have problems with a postback from the button submit as after the button has finished the site think its a full refresh which gives me no chance to show any failure of login message or error,
I cant seem to pinpoint why this is happening and have looked up about the page cycle but can't put my finger on it.
Heres all my code for behind the page
protected void Page_Init(object sender, EventArgs e)
{
Session["user"] = "";
Session["domain"] = "";
Session["manager"] = "";
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
lblError.Text = "This was a post back.";
else
lblError.Text = "This was NOT a post back.";
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Allows the variable to be used through out the app
Session["user"] = username;
Session["domain"] = domain;
Session["manager"] = null;
if (true == authenticateUser(Session["domain"].ToString(), Session["user"].ToString(), password))
Response.Redirect(Response.ApplyAppPathModifier("Update.aspx"));
}
and front
<form id="form1" runat="server" style="Width:19%;" class="pure-form pure- form-stacked">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
<br />
<asp:TextBox ID="txtLoginID" Width="95%" Style="display:inline-block;" runat="server"></asp:TextBox>
</div>
<br/>
<asp:Label ID="lblpwd" runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="txtPassword" Width="95%" TextMode="Password" runat="server"></asp:TextBox>
<asp:Label ID="lbldmn" runat="server" Text="Domain"></asp:Label>
<asp:DropDownList ID="ddlDomain" Width="95%" runat="server">
<asp:ListItem>hdnl.it</asp:ListItem>
<asp:ListItem>yodel.net</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="lblError" runat="server" ForeColor="Red" ></asp:Label>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnLogin" runat="server" Text="Login" Width="95%" OnClick="btnLogin_Click"
CssClass="button-success pure-button" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<div class="overlay"></div>
<div class="modal">
<h2>Please Wait.....</h2>
<img alt="Loading..." src="/Images/loading.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</form>

User is creating when email is in wrong format even though I used the regualr expression validator

I am trying to create a user with the create user wizard. For email validation i am using regualr expression control. I given ControlToValidate property to the id of the email text box. When I given wrong email Id and click on create user it is showing error message what i configured in the <asp:RegularExpressionValidator>but it is going to next step and saying user created succesfully. How to stop register the user when email format is wrong. I am trying to modify the CreatingUser event like this
protected void CreateUserWizard1_CreatingUser(object sender, LoginCancelEventArgs e)
{
bool allfieldsstatus = false;
RegularExpressionValidator emailvalidator = (RegularExpressionValidator)CreateUserWizardStep1.ContentTemplateContainer.FindControl("emailvalidator");
if (!emailvalidator.Visible)
{
allfieldsstatus = true;
}
if (allfieldsstatus)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
But this is not working. The visibility property not at all showing. I tried in another way in if condition as
if(!emailvalidator.ErrorMessage.length!=0)
{
allfieldstatus = true;
}
This is also not working. Because the ErrorMessage property is always be there in configuration of <asp:RegularExpressionValidator >
What is the solution for this?
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
CssClass="createUseWizard" AutoGeneratePassword="True" ContinueDestinationPageUrl="~/Account/AdminRegister.aspx"
CreateUserButtonText="Register User"
OnCreatedUser="CreateUserWizard1_CreatedUser" BorderStyle="None"
DisplayCancelButton="True" oncreatinguser="CreateUserWizard1_CreatingUser"
LoginCreatedUser="False">
<WizardSteps>
<asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
<ContentTemplate>
<div id="registerUserDiv">
<div id="registerUserHeader">
Register New User
</div>
<div>
<div class="registerUserLable">
<asp:Label ID="UserNameLabel" runat="server" Text="User Name" AssociatedControlID="UserName"></asp:Label>
</div>
<div class="inputTextbox">
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator CssClass="showInRed" ID="UserIDrequired" runat="server" ControlToValidate="UserName"
ErrorMessage="Email is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1"
SetFocusOnError="True">*</asp:RequiredFieldValidator>
</div>
</div>
<div>
<div class="registerUserLable">
<asp:Label ID="Label1" runat="server" Text="E-mail" AssociatedControlID="Email"></asp:Label></div>
</div>
<div class="inputTextbox">
<asp:TextBox ID="Email" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator CssClass="showInRed" ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Email" ErrorMessage="E-mail is required." ToolTip="E-mail is required."
ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator>
</div>
<div>
<div class="registerUserLable">
<asp:Label ID="Label2" Text="Select Role" runat="server" />
</div>
<div class="inputTextbox">
<asp:DropDownList ID="rolesDropdown" runat="server">
</asp:DropDownList>
</div>
</div>
<div>
<div class="errorEmail">
<asp:RegularExpressionValidator ID="emailvalidator" runat="server"
ErrorMessage="Email Should be in correct format" ControlToValidate="Email"
SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
Display="Dynamic"></asp:RegularExpressionValidator>
</div>
</div>
<div>
<asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>
</div>
</div>
</ContentTemplate>
</asp:CreateUserWizardStep>
<asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">
</asp:CompleteWizardStep>
</WizardSteps>
</asp:CreateUserWizard>
In general, you should check if validation passed with the IsValid property of single validator controls or of the Page itself:
if (!emailvalidator.IsValid) {
e.Cancel = true;
}
or
if (!Page.IsValid) {
e.Cancel = true;
}
For the wizard, you could perform this check in the NextButtonClick and FinishButtonClick event handlers.
If you think it's RegExp problem try this:
/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i

Categories

Resources